MATLAB Primer-chapter1

Chapter 1 Quick Start

Desktop Basics

When you start MATLAB陶耍,the desktop appears in it's default layout.

default_desktop

The desktop includes these panels

  • Current Folder --- Access your files.
  • Command Windows --- Enter commands at the command line,indicateed by the prompt(>>).
  • Workspace --- Explore data that you create or import from files.

As you work in MATLAB ,you issue(輸入) commands that create variables and call functions.
For example,create a variable named a by typing this statement at the command line:

a = 1

MATLAB adds variable a to the workspace and displays the result in the Command Window.

Create a few more variables.

b = 2
c = a + b
d = cos(a)

When you do not specify an output variable.MATLAB uses the variable ans , short for answer ,to store the results of your calculation.

If you end a statement with a semicolon(分號(hào)),MATLAB performs the computation, but suppresses(抑制) the display of output in the Command Window.

e = a + b;

You can recall previous commands by pressing the up- and down-arrow keys.
Press the arrow keys either at an empty command line or after you type the first few characters of a command.

Matrics and Arrays

MATLAB is an abbreviation for "matrix laboratory" While other programing languages mostly work with numbers one at a time,MATLAB is designed to operate primarily on whole matrices and arrays.

ALL MATLAB variables are multidimensional arrays, no matter what types of data. A matrix is a two-dimensiona(二維)l arrays often used for linear algebra(線性回歸)

Array Creation

To create an array with four elements in a single row, separate the elements with either a comma (,) or a space().

a = [1 2 3]
b = [1,2,3]

This type of array is a row vector.

To create a matrix that has multiple rows, separate the rows with semicolons(;).

a = [1 2 3;4 5 6;7 8 9]

Another way to create a matrix is to use a function, such as ones(),zeros(),orrand(). For example, create a 5-by-1 column vector of zeros.

z = zeros(5,1)

Matrix and Array Operation

MATLAb allows you to process all of the values in a matrix using a single arithmetic operator or function.

a + 10
sin(a)

To transpose a matrix, use a single qoute ('):

a'

MATLAB stores numbers as floating-point values, and arithmetic operations are sensitive to small differences between the actual value and its floating-point representation. You can display more decimal digits using the format command:

format long
p = a * a

format affects only the display of numbers, not the way MATLAB computes or saves them.

To perform element-wise multiplication rather than matrix multiplication, use the .* operator:

p = a.*a

The matrix operators for multiplication, division, and power each have a corresponding array operator that operates element-wise. For example, raise each element of a to the third power:

a.^3

Concatenation

Concatenation is the process of joining arrays to make larger ones. In fact, you made your first array by concatenating its individual elements. The pair of square brackets [] is the concatenation operator.

A = [a,a]

Concatenating arrays next to one another using commas is called horizontal concatenation. Each array must have the same number of rows. Similarly, when the arrays have the same number of columns, you can concatenate vertically using semicolons.

A = [a;a]

Complex Numbers

Complex numbers have both real and imaginary parts, where the imaginary unit is the square root of -1.

sqrt(-1)

To represent the imaginary part of complex numbers, use either i or j.

c = [3+4i,4+3j;-i,10j]

Indexing

Every variable in MATLAB is an array that can hold many numbers. When you want to access selected elements of an array, use indexing.

For example, consider the 4-by-4 magic square A:

A = magic(4)

There are two ways to refer to a particular element in an array. The most common way is to specify row and column subscripts, such as

A(4,2)

Less common, but sometimes useful, is to use a single subscript that traverses down each column in order:

A(8)

Using a single subscript to refer to a particular element in an array is called linear indexing.

If you try to refer to elements outside an array on the right side of an assignment statement, MATLAB throws an error.

test = A(4,5)
**Index exceeds matrix dimensions**.

However, on the left side of an assignment statement, you can specify element outside the current dimensions. The size of the array increases to accommodate the newcomers.

A(4,5) = 7

To refer to multiple elements of an array, use the colon(:) opertor, which allows you to specify a range of the form start:end. For example,list elements in the first three rows and the second column of A:

A(1:3,2)

The colon alone, without start or end values, specifies all of the elements in that dimension. For example, select all the columns in the third row of A:

A(3,:)

The colon operator also allows you to create an equally spaced vector of values using the more general form start:step:end.

If you omit the middle step, as in start:end,MATLAB uses the default step value of 1.

Workspace Variables

The workspace contains variables that you create within or import into MATLAB data files or other programs. For examples, these statements create variables A and B in the workspace.

A = magic(4);
B = rand(3,5,2);

you can view the contents of the workspace using whos

Workspace variables do not persist after you exist MATLAB. Save your data for later use with the save command.

save myfile.mat

Saving preserves the workspace in your current working folder in a compressed file with a .mat extension, called a MAT-file.

To clear all the variables from the workspace, use the clear command.

Restore data from a MAT-file into the workspace using load.

load myfile.mat

Text and Characters

When you are working with text, enclose sequences of characters in single quotes can assign text a variable.

myText = 'Hello , world';

If the text incloudes a single quote, use two single quotes within the definition.

otherText = 'your''re right';

myText and otherText are arrays, like all MATLAB variables. Their class or data type is char,which is short for character.

whos myText

You can concatenate character arrays with square brackets, just as you concatenate numeric arrays.

longText = [myText, ' - ',otherText];

To convert numeric values to characters, use functions, such as num2str() or int2str().

f = 71;
c = (f - 32)/1.8;
tempText = ['Temperature is ',num2str(c),'C']

Calling Functions

MATLAB provides a large number of functions that perform computational tasks.Functions are equivalent to subroutines or methods in other programming languages.

To call a function, such as max(),enclose its input arguments in parentheses:

A = [1 2 5];
max(A);

If there are multiple input arguments,separate them with commas:

B = [10 6 4];
max(A,B)

Return output from a function by assigning it to a variable:

maxA = max(A);

When there are multiple output arguments, enclose them in square brackets:

[maxA,location] = max(A)

Enclose any character inputs in single qoutes:

disp('hello world')

To call a function that does not require any inputs and does not return any outputs, type only the function name:

clc

The clc function clears the Command Window.

2-D and 3-D Plots

Line Plots

To create two-dimensional line plots, use the plot() function. For example, plot the value of the sine function from 0 to 2pi:

x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)

You can label the axes and add a title.

xlabel('x');
ylabel('y');
title('plot of the sine function');

By adding a third input argument to the plot function, you can plot the same variables using a red dashed line.

plot(x,y,'r--');

The 'r--' string is a line specification. Each specification can include characters for the line color,style,and marker. A marker is a symbol that appears at each plotted data point, such as a +,o,or *. For example, 'g:*' requests a dotted green line with * markers.

Notice that the titles and labels that you defined for the first plot are no longer in the current figure windows. By default, MATLAB clears the figure each time you call a plotting function, resetting the axes and other elements to prepare the new plot.

To add plots to an existing figure, use hold.

x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y,'r--');

hold on;

y2 = cos(x);
plot(x,y2,'g:-');
legend('sin','cos');

Until you hold off or close the window,all plots appears in the current figure window.

3-D Plots

Three-dimensional plots typically display a surface defined by a function in two variables, z = f(x,y).

To evaluate z,first create a set of (x,y) points over the domain of the function using meshgrid.

[x,y] = meshgrid(-2:.2:2);
z = x .* exp(-x.^2 - y.^2);

Then, create a surface plot.

surf(x,y,z)

Both the surf function and its companion mesh display surfaces in three dimensions. surf displays both the connecting lines and the faces of the surface in color. mesh produces wireframe surfaces that color only the lines connecting the defining points.

Subplots

You can display multiple plots in different subregions of the same window using the subplot function.

The first two inputs to subplot indicate the number of plots in each row and column. The third input specifies which plot is active. For example, create four plots in a 2-by-grid within a figure window.

t = 0:pi/10:2*pi;
[x,y,z] = cylinder(4*cos(t));
subplot(2,2,1);mesh(x);title('x');
subplot(2,2,2);mesh(y);title('y');
subplot(2,2,3);mesh(z);title('z');
subplot(2,2,4);mesh(x,z,y);title('x,y,z');

Programming and scripts

The simplest type of MATLAB program is called a script. A script is a file with a .m extension that contains multiple sequential lines of MATLAB commands and function calls. You can run a script by typing its name at the command line.

Sample Script

To create a script, use the edit command,

edit plotrand

This opens a blank file named plotrand.m. Enter some code that plots a vector of random data:

n = 50;
r = rand(n,1);
plot(r);

Next, add code that draws a horizontal line on the plot at the mean:

m = mean(r);
hold on
plot([0,n],[m,m])
hold off
title('Mean of Random Uniform Data')

Whenever you write code, it is a good practice to add comments that describe the code.Comments allow others to understand your code, and can refresh your memory when you return to it later. Add comments using the percent(%)symbol.

%Generate random data from a uniform distribution
%and calculate the mean. Plot the data and the mean.
number = 50; %50 data points
r = rand(number,1);
plot(r);

%Draw a line from (0,m) to (n,m)
m = mean(r);
hold on
plot([0,n],[m,m])
hold off
title('Mean of Random Uniform Data')

Loops and Conditional Statements

Within a script, you cna loop over sections of code and conditionally execute sections using the keywords for,while,if, and switch.

For example, create a script named calcmean.m that uses a for loop to calculate the mean of five random samples and the overall mean.

nsamples = 5;
npoints = 50;

for k = 1 : nsamples
    currentData = rand(npoints,1);
    sampleMean(k) = mean(currentData)
end

overallMean = mean(sampleMean)

Now, modify the for loop so that you can view the results at each iteration. Dispaly in the Command Window that includes the current iteration number, and remove the semicolon from the assignment to sampleMean.

for k = 1 : nsamples
    iterationString = ['Iteration #',int2str(k)];
    disp(iterationString)
    currentData = rand(npoints,1);
    sampleMean(k) = mean(currentData)
end
overallMean = mean(sampleMean)

In the Editor, add conditional statements to the end of calcmean.m that disp a different message depending on the value of overallMean.

if overallMean < .49
    disp('Mean is less than expected')
elseif overallMean > .51
    disp('Mean is greater than expected')
else
    disp('Mean is within the expected range')
end

Script Locations

MATLAB looks for scripts and other files in certain places. To run a script, the file must be in the current folder or in a folder on the search path.

By default, the MATLAB folder that the MATLAB Installer creates is on the search path. If you want to store and run programs in another folder, add it to the search path. Select the folder in the Current Folder browser, right-click, and then select Add to path.

Help and Documentation

All MATLAB functions have supporting documentation that includes examples and describes the function inputs, outputs, and calling syntax. There are several ways to access this information from the command line:

  • Open the function documentation in a separate windows using the doc command.
    doc mean
  • Disp function hints(the syntax portion of the function documentation) in the Command Window by pausing after you type open parentheses for the function input arguments.
    mean(
  • View an abbreviated text version of the function documentation in the Command Window using the help command.
    help mean

學(xué)習(xí)自MATLAB官方手冊(cè)-2017a

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末违柏,一起剝皮案震驚了整個(gè)濱河市记劝,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌论笔,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,542評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異祟牲,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)抖部,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門说贝,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人慎颗,你說(shuō)我怎么就攤上這事乡恕。” “怎么了俯萎?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,912評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵傲宜,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我夫啊,道長(zhǎng)函卒,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,449評(píng)論 1 293
  • 正文 為了忘掉前任撇眯,我火速辦了婚禮报嵌,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘熊榛。我一直安慰自己锚国,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,500評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布玄坦。 她就那樣靜靜地躺著血筑,像睡著了一般。 火紅的嫁衣襯著肌膚如雪煎楣。 梳的紋絲不亂的頭發(fā)上云挟,一...
    開(kāi)封第一講書(shū)人閱讀 51,370評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音转质,去河邊找鬼园欣。 笑死,一個(gè)胖子當(dāng)著我的面吹牛休蟹,可吹牛的內(nèi)容都是我干的沸枯。 我是一名探鬼主播日矫,決...
    沈念sama閱讀 40,193評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼绑榴!你這毒婦竟也來(lái)了哪轿?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,074評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤翔怎,失蹤者是張志新(化名)和其女友劉穎窃诉,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體赤套,經(jīng)...
    沈念sama閱讀 45,505評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡飘痛,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,722評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了容握。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片宣脉。...
    茶點(diǎn)故事閱讀 39,841評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖剔氏,靈堂內(nèi)的尸體忽然破棺而出塑猖,到底是詐尸還是另有隱情,我是刑警寧澤谈跛,帶...
    沈念sama閱讀 35,569評(píng)論 5 345
  • 正文 年R本政府宣布羊苟,位于F島的核電站,受9級(jí)特大地震影響感憾,放射性物質(zhì)發(fā)生泄漏践险。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,168評(píng)論 3 328
  • 文/蒙蒙 一吹菱、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧彭则,春花似錦鳍刷、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,783評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至芬萍,卻和暖如春尤揣,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背柬祠。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,918評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工北戏, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人漫蛔。 一個(gè)月前我還...
    沈念sama閱讀 47,962評(píng)論 2 370
  • 正文 我出身青樓嗜愈,卻偏偏與公主長(zhǎng)得像旧蛾,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子蠕嫁,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,781評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容