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(分号),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

学习自MATLAB官方手册-2017a

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,776评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,527评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,361评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,430评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,511评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,544评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,561评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,315评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,763评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,070评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,235评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,911评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,554评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,173评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,424评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,106评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,103评论 2 352

推荐阅读更多精彩内容