Академический Документы
Профессиональный Документы
Культура Документы
MATLAB Tutorial
1.1 Introduction to MATLAB
In MATLAB all data are represented as matrices. Here are some examples:
a = 1 a = a = a =
1 matrix (a scalar). 1 2 3] is a row vector. a' is a column vector. 'hello' is a row vector of ascii code numbers (stored as double oats) and the representation of a string.
is a 1
The 1 1 matrix (the scalar) is treated specially for most mathematical operations. Twodimensional matrices are implicitly also one-dimensional with column major.
is the matrix
1 This tutorial, for use in CNS/CS/EE 182, is a compilation of material from the MATLAB User's Guide and the book Handbook for Matrix Computations by Thomas F. Coleman and Charles Van Loan.
2
2
where the n entries for each row are separated by one or more blanks. You can also make your input look like what you want your output to be when setting up matrices.
A= 1 2 3 4]
and A=
1 2;3 4]
then if you enter B(1,3)=1 it will add another column to B with the topmost entry being a one. The row and column dimensions of an array can be computed with the built-in function
size
m,n]=size(B)
This assigns the row dimension of B to m and the column dimension to n. If v is either a row or column vector then the function length(v) returns the dimension of v. Subscripts in MATLAB must be positive. Fractional subscripts are oored.
() () () ()
= v= v= v=
v
1 2 3]
3 2 1 0]
1 2 3]
1 3 5 7 9]
The starting value, increment, and terminating value may be determined by expressions, and they need not be integers.
returns
w(i)=10^ a+(i-1)(b-a)/(n-1)]
For example,
w=logspace(0,3,4)
() w=
1 10 100 1000]
Special Matrices
A=eye(m,n) = A -by- , ones diagonal, zeros elsewhere A=zeros(m,n) = A -by- , zeros everywhere A=ones(m,n) = A -by- , ones everywhere A=rand(m,n) = A -by- , random numbers 0,1]
) m n ) m n ) m n ) m n
Complex Matrices
If A and B are real matrices with the same dimension and i2 = 1, then the complex matrix C = A + iB can be generated:
C=A+sqrt(-1)*B
Note that i must be speci cally set to be equal to sqrt(-1) if expressions such as D= are to be used.
1+i;1-i]
Block Matrices
If A11, A12, A21, A22, A31 and A32 have dimensions where
2 3 5
makes sense, then this block matrix can be setup in MATLAB with the command
A= A11 A12; A21 A22; A31 A32]
1.2.1 Submatrices
If A is m-by-n and the integers i, j , p and q satisfy 1 i j
2
B=A(i:j,p:q)
=) B = 6 ... 4
2
aip
ajp a1 p amp
. . .
3 7 5
B=A(:,p)
=) B =6 4
B=A(i:i+1,3:-1:2)
Also for non-contiguous extractions you can specify the rows and columns wanted explicitly
B=A( 1 3 5], 2 4])
3 5
replaces the qth column of A with w. You can also use this technique to delete rows and columns (note that matrix) .
A(i:j,:)= ] ]
() A=A
(1:i-1,:); A(j+1:m,:)]
Relations
A relation has the form
returns T=
if
1 1; 0 1]
Constr<uctions
if frelationg fstatementsg end
Thus,
if print flag > 0 A end
>
returns "1" if any vi >1 and "0" otherwise. If the function all is applied to a vector then it returns a "1" if all the entries are nonzero, else it returns a "0."
For example,
for i=1:3 x(i)=i; end
is equivalent to x= 1; 2; 3];. As an aside, we note that ending a command with ; supresses the output from the command. While loops have the general form
while frelationg fstatementsg end
1.4. GRAPHICS
The break command can be used to terminate a loop. The following prints all Fibonnaci numbers less than 1000:
fib(1)=1 fib(2)=1 for j=3:1000 z=fib(j-1)+fib(j-2); if z>=1000 break end fib(j)=z end
When a break command is encountered in the body of a loop the loop is immediately terminated.
1.4 Graphics
Elementary Plotting Functions
plot
creates a plot of vectors or columns of matrices. creates a plot using logarithmic scales for both axes. creates a plot using a logarithmic scale for the x axis and a linear scale for the y creates a plot using a logarithmic scale for the y axis and a linear scale for the x
loglog
semilogx
axis.
semilogy
axis.
title
adds a title to the graph. adds a label to the x-axis. adds a label to the y-axis.
Creating a Plot
If y is a vector, plot(y) produces a linear graph of the elements of y versus the index of the element of y. If you specify two vectors as arguments, plot(x, y) produces a graph of y vs. x. You can also specify multiple sets of data and de ne the line style and color to use for each in a single call.
t = 0:pi/100:2*pi;
produces a graph of y1 vs. x and y2 vs. x on the same axis, one with a red solid line, the other with a green dashed line style. You can add lines to an existing graph using the hold statement. When you set hold to on, MATLAB does not remove the existing lines. It may rescale the axes if the new data falls outside of the range of the previous data plotted.
Multiple Plots
You can display multiple plots in the same window or print them on the same piece of paper with the subplot function. subplot(m,n,p) breaks the gure window into an mxn matrix of small subplots and selects the pth subplot as the current plot. To create multiple windows use the gure function. Figure(n) makes the nth gure the current gure.
1.5. FUNCTIONS
t = 1:n; ts = 1:0.1:n; xs = spline(t,x,ts); ys = spline(t,y,ts); plot(xs,ys,'c-'); hold off
One nice way of adding text to your graph is gtext('string'). The crosshair appears in the graph window and when you click the mouse the text string will appear in the graph to the right of the point where you clicked.
1.5 Functions
The main MATLAB toolbox provides all the base functions needed to perform any sort of data analysis. For instance, the group of functions that provides basic data analysis capabilities are: max, min, mean, median, std and diff. In general, for built-in functions, with vector arguments it does not matter whether the vectors are oriented in a row or column direction and with array arguments the functions operate in a column-oriented fashion on the data in the arrays. These functions can be used to construct user-de ned functions, stored in the form of a .m le. The general structure of a .m le is: The rst line in the function de nition is of the form function fvariableg,fvariableg] = ffunction nameg(fargumentsg) Comments begin with the "%" sign. All functions should begin with "how-to-use" comments, to be displayed when the help command is used. Output messages can be displayed with commands of the form disp('fmessageg') The variables used by a function that do not appear in the function statement are local unless they have been declared global. A function can be referred to in an expression so long as it makes dimensional sense. It is legal for a function to call other functions, built-in or user-de ned.
Example
function y=prodAx(A,x) % % This function returns a unit 2-norm vector in the % direction of Ax, where A is n-by-n and x is n-by-1 % y=A*x; c=norm(y); if c ~=0 y=y/c; else y=1; zeros(length(x)-1,1);
10
Example
function F=afun(A,f)} % % If A is an m-by-n matrix and f is the name of either a built-in % or user-defined function that operates on scalars, then this function % returns an m-by-n matrix F with F(i,j)=f(A(i,j)). The name of f must % be in quotes, e.g., F=afun(A,'cos') sets F(i,j) to cos(A(i,j)). % m,n]=size(A); for j=1:m for i=1:n F(i,j)=eval( f,'(A(i,j))']); end end
which clearly must assign f (A(i; j )) to F (i; j ): A string in MATLAB is a row vector whose entries are characters. Strings are speci ed by enclosing them in quotes. Thus,
s1='cos'
assigns the three-character string of cos to the string s1. The built-in function eval takes a string and executes it, assuming that the string is a meaningful MATLAB statement. Thus,
eval('y=A*x')
is equivalent to y=A*x.
11
The data can be retrieved with the load f lenameg command. The whole contents of the speci ed le is then loaded back into MATLAB.