Chapter 1 Quick Start
Desktop Basics
When you start MATLAB,the desktop appears in it's default layout.
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