Вы находитесь на странице: 1из 11

Chapter 1

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.

1.2 Entering Matrices


The MATLAB language contains no dimension statements or type declarations. The convention for entering matrices with explicit lists is: Separate a explicit list of elements with blanks or commas Surround the elements with brackets, ] Use the semicolon to indicate the ends of rows
A= 1 2 3;4 5 6;7 8 9]

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

CHAPTER 1. MATLAB TUTORIAL


A=4
1 2 3 4 5 6 7 8 9
3 5

In general, to set up an m-by-n matrix A use the format


A=

frow 1g;frow 2g;...;frow mg]

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]

are the same.

Dimensioning and Subscripts


Dimensioning is handled automatically in MATLAB. Suppose A= 1 2 3;4 5 6] but then is overwritten with the input A= 1 2;3 4]. MATLAB will change the internal representation into a 2-by-2 matrix. MATLAB does other types of auto-dimensioning as well. MATLAB will make a structure just large enough so that the assignment makes sense. For instance, if B is uninitialized then the command B(3,2)=5 gives the output of
B= 0 0 0 0 0 5

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.

The Colon Method for Entering Vectors


Colons can be used to prescribe vectors whose components di er by a xed increment. For instance,

1.2. ENTERING MATRICES


=1:3 v=3: 1:0 v = 1 : 2 : 10 i = 1; j = 3; v = i : j
v

() () () ()

= 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.

Logarithmically Spaced Vectors


The function logspace can be used to generate logarithmically regular vectors. The vector returned with the command
w=logspace(a,b,n)

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]

CHAPTER 1. MATLAB TUTORIAL

Block Matrices
If A11, A12, A21, A22, A31 and A32 have dimensions where
2 3 5

A11 A12 A = 4 A21 A22 A31 A32

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)

m and 1 p q n then aiq ajq


.. .
3 7 5

=) 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)

=) B = a ai3 a ai2 i+1;3 i+1;2

Also for non-contiguous extractions you can specify the rows and columns wanted explicitly
B=A( 1 3 5], 2 4])

a12 a14 =) B = 4 a32 a34 a52 a54

3 5

It is also possible to make an assignment to a submatrix. For instance,


A(:,q)=w'

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,:)= ] ]

denotes the empty

() A=A

(1:i-1,:); A(j+1:m,:)]

1.3. CONTROL STRUCTURES

1.3 Control Structures

Relations
A relation has the form

f matrix expression g f relational operator g f matrix expression g


where the following are legal relational operators: == equals ~ = not equals < less than <= less than or equal to > greater than >= greater than or equal to & AND j OR ~ NOT The value of a relation is a 0-1 matrix that has the same size as the matrix expressions in the relation. The 1's appear everywhere the relation holds. For example,
A= 1 2; 3 4] B= 1 2;2 4] T= A==B

returns T=
if

1 1; 0 1]

Constr<uctions
if frelationg fstatementsg end

The if statement has the form

Thus,
if print flag > 0 A end

prints A if print flag is positive. If-then-else constructs are also possible.

CHAPTER 1. MATLAB TUTORIAL

The "any" and "all" functions


The any and all functions can be used to sense the zero-nonzero structure of a matrix. If any is applied to a vector it returns a "1" if any component of the vector is nonzero. Otherwise, it returns a "0." Thus, if v is a vector then
any(v ones)

>

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 Loops and While Loops


for loops have the form
for fvarg = frow of counter valuesg fstatementsg end

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

For example the equivalent to w=any(v) is


w=0 k=1 while k<=length(v) & w==0 if v(k) =0 w=1 end k=k+1 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.

xlabel ylabel gtext grid

places text on the graph using the mouse.

turns grid lines on axis scales display axes.

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;

CHAPTER 1. MATLAB TUTORIAL


x = sin(t); y1 = sin(t+.25); y2 = sin(t+.5); plot(x,y1,'r-',x,y2,'g--') title('Phase Shift'); xlabel('x') ylabel('y1 and y2')

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.

Graphical Input and Output


The ginput function allows you to use the mouse or the arrow keys to select points on a plot. It returns the coordinates of the pointers position; either the current position or the position when a mouse button or key is pressed. In the following example, a sequence of points, x, y], in the plane is selected with ginput. Then two one- dimensional splines are passed through the points, evaluated with a spacing 1/10th of the original spacing, and plotted.
% start with a clean slate clf axis( 0 10 0 10]) hold on % initially, the list of points is empty x = ]; y = ]; n = 0; % loop, picking up the points. disp('Left mouse button picks points.') disp('Right mouse button picks last point.') but = 1; while but==1 xi,yi,but]=ginput(1); plot(xi,yi,'go') n=n+1; x(n,1)=xi; y(n,1)=yi; end % interpolate with two splines and finer spacing

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

CHAPTER 1. MATLAB TUTORIAL


disp('Matrix-vector product is zero. First column of I returned.') end

Passing Function Names


It is possible to pass the name of a function to another function, but it requires some text processing with the eval function.

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

To understand this function we need to understand the statement


F(i,j)=eval( f, 'A(i,j))']);

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.

1.6 Saving and Restoring Data


To see what data you have in the workspace use either of the commands who and whos. All the data in the workspace can be save in a le using the command save f lename g . It

1.6. SAVING AND RESTORING DATA


is possible to specify a subset of variables to be saved:
save

11

fvar1g . . . fvarng f lenameg

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.

Вам также может понравиться