Sunteți pe pagina 1din 15

A Guide to MATLAB

Rev.: 09/2007

Some basic use of MATLAB is introduced, and some exercises are provided at the end of each section below. You should finish them yourselves, and if necessary, you can check the suggested solution at the end of this document. A. HELP facility A help facility provides online information for most MATLAB topics. The command help <enter> it displays a list of directories that contains MATLAB related files as below. HELP topics: matlab\general matlab\ops matlab\lang matlab\elmat matlab\elfun matlab\specfun matlab\matfun matlab\datafun matlab\polyfun matlab\funfun General purpose commands. Operators and special characters. Programming language constructs. Elementary matrices and matrix manipulation. Elementary math functions. Specialized math functions. Matrix functions - numerical linear algebra. Data analysis and Fourier transforms. Interpolation and polynomials. Function functions and ODE solvers.

The help followed by specific MATLAB commands, functions, and symbols, provides detailed information about the feature. Example ,

Command Window

Type in help matlab\elfun and press <enter> A list of commonly used math functions show. Take a look on it. In the middle of the list, you will see how a complex number is defined.

The listed commands relating complex numbers are abs - Absolute value. angle - Phase angle. complex - Construct complex data from real and imaginary parts. conj - Complex conjugate. imag - Complex imaginary part. real - Complex real part. To see how to use the command complex, Key in the following in the command line >>help complex <enter> it returns the following,
COMPLEX Construct complex result from real and imaginary parts. C = COMPLEX(A,B) returns the complex result A + Bi, where A and B are identically sized real N-D arrays, matrices, or scalars of the same data type. Note: In the event that B is all zeros, C is complex with all zero imaginary part, unlike the result of the addition A+0i, which returns a strictly real result. C = COMPLEX(A) for real A returns the complex result C with real part A and all zero imaginary part. Even though its imaginary part is all zero, C is complex and so isreal(C) returns false. Note that the expression A+i*B or A+j*B will give identical results for nonzero B if A and B are double-precision and i or j has not been assigned. Use COMPLEX if ambiguity in the variables "i" or "j" might arise, or if A and B are not double-precision, or if B is all zero. See also I, J, IMAG, CONJ, ANGLE, ABS, REAL, ISREAL.

Exercise A: (a). Use help command to see how to use the command angle . (b). By use of both the commands angle and complex, construct and type in a command line in the matlab command window to find the phase angle of a complex number (1+2j). What is the unit of the phase angle? (c). Similarly, find out the magnitude of this complex number with matlab.

B. Definition of Variables Variables are assigned by typing in the expression directly, for example, typing >> a = 1+2 a= 3 Answer will not be displayed when a semicolon (;) is put at the end of an expression, for example, >> a = 1+2; MATLAB utilizes the following arithmetic operators:
+ * / ^ ' addition subtraction multiplication division power operator transpose

A variable can be assigned using a formula that utilizes these operators and/or previously defined variables. For example, since a was defined previously, the following expression is valid >> b = 2*a; To find the value of a previously defined quantity, type the quantity by itself: >> b b= 6 If your expression does not fit on one line, use an ellipsis (three or more periods at the end of the line) and continue on the next line. >> c = 1+2+3+... <enter> >> 5+6+7; More about the matlab windows:

All currently defined variables will be listed out in the Workspace.

Workspace

Command Window

Statements you enter in the Command Window are logged in the Command History. In the Command History, you can view previously run statements, and copy and execute selected statements.

Command History

Exercise B: (a) Compute the value of the function y = x 2 e 2 x sin(3x ) when x = 5.


3

C. Definition of Matrices MATLAB is based on matrix and vector algebra; even scalars are treated as 1x1 matrices. Therefore, vector and matrix operations are as simple as common calculator operations. Vectors can be defined in two ways. The first method is used for arbitrary elements: >> v = [1 3 5 7] v= 1 3 5 7 v represents a 1 x 4 vector with elements 1, 3, 5 and 7. Note that commas could have been used in place of spaces to separate the elements. Additional elements can be added to the vector: >> v(5) = 8; the fifth element is added to v, resulting in vector v = [1 3 5 7 8]. Previously defined vectors can be used to define a new vector. For example, with v defined above >> a = [9 10]; >> b = [v a]; it creates the vector b = [1 3 5 7 8 9 10]. The following method is used for creating vectors with equally spaced elements: >> t = 0 : 0.5 : 5 it creates a 1x11 vector with the elements 0, 0.5, 1, 1.5, 2, 2.5.....,5. Note that the middle number 0.5 defines the increment. If only two numbers are given, then the increment is set to 1 by default. For example, >> k = 0:10 creates a 1x11 vector with the elements 0, 1, 2, 3, .....9, 10. Matrix elements can be defined by any MATLAB expression; for example >> x = [ -1 sqrt(4) (1+2+3)*2/12] x= -1 2 1

Individual matrix elements can be referenced with indices inside parentheses, ( ). Continuing the example >> x (5)=4 x= -1 2 1 0 4

Notice that the size of x is automatically increased to accommodate the new element and that the undefined intervening elements are set to zero.

You can construct large matrices using small matrices as elements. For example, to attach another row to matrix A: >> r = [10 11 12]; >> A=[1 2 3; 4 5 6; 7 8 9] A= 1 4 7 >>A=[A ; r] A= 1 4 7 10 2 5 8 11 3 6 9 12 2 5 8 3 6 9

You can extract small matrices from large matrices using a colon (:) . For example, take the first three rows and all columns of the current A and returns the original A, i.e. >>A=A(1:3 , : ) A= 1 2 3 4 5 6 7 8 9 Individual matrix elements can be referenced by enclosing their subscripts in parentheses. An expression used as a subscript is rounded to nearest integer. For example, take the element in 2nd row and 3rd column, i.e. >>A( 2 , 3 ) ans = 6

Exercises C: (a) Construct a matrix A where 1 2 A= 10 3 3 4 9 2 5 6 8 1 7 8 7 0

(b) Construct matrix B from A where B takes only the 3 & 4 columns of rows 2 & 3.

D. Getting Workspace Information The previous examples have created variables that are stored in MATLAB workspace. To list the variables in the workspace (or look at the workspace window), enter >>who This shows these examples have generated three variables. To see the size of the current variables, you can use whos.

E. Matrix Operations Transposing Matrix The special character ' (prime or apostrophe) denotes the transpose of matrix. >>B=A' B= 1 4 7 2 5 8 3 6 9 and >>x=[-1 0 2]' x= -1 0 2 The prime ' transposes matrices in a formal sense; if Z is a complex matrix, then Z' is its complex conjugate transposed. For an unconjugated transpose, use Z.' or conj(Z'). Adding and Subtracting Matrices The symbols + and - denote addition and subtraction of matrices. The operations are defined whenever the matrices have the same dimensions. For example, with the above matrices, A+x is not correct because A is 3-by-3 but x is 3-by-1. However, it is accepted, A & B have the same dimensions, >>C = A + B C= 2 6 10 6 10 14 10 14 18

Addition and subtraction are also defined if one operand is a scalar, that is a 1-by-1 matrix. In this case, the scalar is added or subtracted from all elements of the other operand. For example >> y = x -1 gives y= -2 -1 1

Multiplying Matrices The symbol * denotes multiplication of matrices. Matrix-vector products are special cases of general matrix-matrix products. For this example A times x, i.e. >>b=A*x is allowed and results in the output b= 5 8 11 Naturally, a scalar can multiply, or be multiplied by, any matrix: >>2*x ans = -2 0 4

F. Array Operations Adding and Subtracting Arrays For addition and subtraction, the array operations and the matrix operations are the same, so + and - can be regarded as either matrix or array operations. Multiplying and Dividing Arrays The symbol .* denotes array, or elements-by-elements, multiplication. If A and B have the same dimensions, then A.*B denotes the array whose elements are simply the products of the individual elements of A and B. For example, if >> x = [1 2 3]; y= [ 4 5 6]; >> z = x.*y z= 4 10 18

Using Powers With Arrays The symbol .^ denotes element-by-element powers. Here are several examples, using the above vectors, x and y. Typing >>z = x.^y z= 1 32 729

The exponent can be scalar: >>z=x.^2 z= 1 4 9 Functions are applied element by element. For example, >> t = 0:10; >> x = cos(2*t); creates a vector x with elements equal to cos(2t) for t = 0, 1, 2, ..., 10. Operations that need to be performed element-by-element can be accomplished by preceding the operation by a ".". For example, to obtain a vector x that contains the elements of x(t) = tcos(t) at specific points in time, you cannot simply multiply the vector t with the vector cos(t). Instead you multiply their elements one by one (element-by-element): >> t = 0:10; >> x = t.*cos(t);

Relation and Logical Operations Six relational and logical operators are available for comparing two matrices of equal dimensions. For details, type command >>help ops

Exercise F: (a) Generate a vector x such that

x (n ) = 12e n cos(0.125n )

n [0,1,2,,10]

(b) Generate a 5x5 matrix M whose element M ( x , y) = x 2 y .

G. Control flow FOR Loops MATLAB has its own version of the FOR loop found in computer languages. It allows a statement, or group of statements, to be repeated for a fixed or predetermined number of times. The general form for a FOR loop is for v = expression statements end For example, >>for i = 1:2 >> for j = 1:3 >> D(i,j)=i+j; >> end >>end results in D= 2 3 3 4 4 5

WHILE Loops The general form of a WHILE loop is while expression statements end IF Loops The general form of IF loops if expression statements elseif expression statements else statements end

Exercise G: (a) Using FOR Loops, generate a 4x4 complex matrix Y whose elements Y( x , y) = x 2 xyj. (b) Using FOR and IF Loops, define a matrix Z whose element is 1, | Y( x , y) |> 3 Z( x , y) = 0, otherwise

H. 2-D Graphics MATLAB provides a variety of functions for displaying data as 2-D graphs and for annotating these graphs. This section describes these functions and provides examples of some typical applications. Creating a Plot If y is vector, plot (y) produces a linear graph of elements of y versus the index of the elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x. You can also specify multiple sets of data and define the line style and color to use for each set of data in a single call to plot:
x=sin(t),ysin(t) 1

>>t=0 : pi/100 : 2*pi; >>x=sin(t); >>y=cos(t); >>plot(t , x , 'r-' , t , y , 'g--' ), grid on >>title('x=sin(t),ysin(t)') >>xlabel('t')

0.8 0.6 0.4 0.2 0 -0.2 -0.4 -0.6 -0.8 -1

3 t

The command line : >>plot(t , x , 'r-' , t , y , 'g--' ) produces a graph of x versus t and y versus t on the same axes. The first set of data is plotted with a red solid line and the second set is plotted with a green dashed line. These statements add a title to graph and label the axes: >>title('x=sin(t),ysin(t)') >>xlabel('t')

Use help command, >> help plot , to see more about the plot Other useful commands: stem, stairs, hist, hold, legend. Exercise H: (a). Plot y(t) and z(t) on the same graph , for 5 >t >1, such that

y( t ) = 3e 0.5 t cos(t 2 ) z ( t ) = 1 y( t )

10

I. Scripts When you invoke a script (called M-file), MATLAB simply executes all the command lines found in the script file. Scripts can operate on existing data in the workspace, or they can create new data on which to operate. Any variables that they create remain in the workspace so you can use them in further computations. You are going to create a text file called testing.m and store it under D:/matlab/mfiles/ , here is the content of the testing.m file,
% comment text -- testing.m script clear % remove all variables from the workspace x = 2*pi*[ 0 : 0.1 : 1 ] ; y = sin(x) ; stem (y) % plot Y with the data sequence Y as stems from the x axis

Once the testing.m file is ready, you can run it directly in the matlab command window. Follow the steps below to create and run this script, - Create the directory D:/matlab/mfiles and then choose it as the current directory here.

D:/matlab/mfiles

- Then click on File New M-file, then in the pop-up window type in the content of the testing.m file there, save and close it.

- Now you can run the testing.m in the matlab command window, in the command window, >> testing <enter> - Then a stem graph appears, and the variables used (x and y) are shown in the workspace window.
11

J. Functions You can add new functions to the MATLAB vocabulary by expressing them in terms of existing functions. The existing commands and functions that compose the new function store in M-file (the script in the last section is simply a file containing a sequence of MATLAB statements). Functions make use of their own local variables and accept input arguments. The M-file name, less its extension, is what MATLAB searches for when you try to use the script or function. The name of a function, as defined in the first line of the function M-file, should be the same as the name of the file without the .m extension. Function M-file can accept input and return output arguments. Functions operate on variables within their own workspace, separate from the workspace you access at that MATLAB command prompt. MATLAB requires that M-files must be stored either in the current working directory or in a directory that is specified in the MATLAB path list. For example, the M-files to be used are now stored in a directory called "D:\matlab\mfiles", in order to access these M-files either change the current working directory to D:\matlab\mfiles or permanently add this directory in MATLAB by clicking on File Set Path. Example: Create a function M-file, named yplusx.m under D:/matlab/mfiles. The content of the file is as follows.
function z = yplusx ( y , x ) z = y + x;
two input arguments, x & y one output argument

To demonstrate how this function M-file works in matlab command window:


>> yplusx(2,3) ans =5 >> B = yplusx(4,5) B =9 >> C = yplusx(B,2) C = 11

Exercise J: (a) Given tha

y( t ) = 3e 0.5 t cos(t 2 )

5>t>1

Write a function to plot y(t-t0). The output should show the plot of y(t-t0) together with the original y(t), then use the function to plot y(t- t0) for t0 = 0.5.

12

Suggested Solution of the Exercises Exercise A: (b). angle : unit in radian. >>angle(complex(1,2)) ans 1.1071 (c). >>abs(complex(1,2)) ans 2.2361 Exercise B: (a) >> y=5^2*exp(-2*5)*sin(3*5) y= 7.3808e-004 Exercise C: (a) >> A=[1 3 5 7; 2 4 6 8; 10 9 8 7; 3 2 1 0] A= 1 2 10 3 (b) >> A(2:3, 3:4) ans = 6 8 8 7 3 4 9 2 5 6 8 1 7 8 7 0

Exercise F: (a) >> n=0:10; >> x=12*exp(-n).*cos(0.125*pi*n) x= Columns 1 through 6 12.0000 4.0785 1.1484 0.2286 0.0000 -0.0309

Columns 7 through 11 -0.0210 -0.0101 -0.0040 -0.0014 -0.0004


13

Exercise F: (b) >> y=[1:5;1:5;1:5;1:5;1:5]; >> x=(y').^2; >> M=y.*x M= 1 2 3 4 8 12 9 18 27 16 32 48 25 50 75 4 5 16 20 36 45 64 80 100 125

Exercise G: (a) >>for x=1:4 for y=1:4 Y(x,y)=x^2-x*y*j; end end >> Y Y= 1.0000 - 1.0000i 4.0000 - 2.0000i 9.0000 - 3.0000i 16.0000 - 4.0000i 1.0000 - 2.0000i 1.0000 - 3.0000i 1.0000 - 4.0000i 4.0000 - 4.0000i 4.0000 - 6.0000i 4.0000 - 8.0000i 9.0000 - 6.0000i 9.0000 - 9.0000i 9.0000 -12.0000i 16.0000 - 8.0000i 16.0000 -12.0000i 16.0000 -16.0000i

(b) >> for x=1:4 for y=1:4 if abs(Y(x,y)) > 3 Z(x,y)=1; else Z(x,y)=0; end end end >> Z Z= 0 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1

14

Exercise H: (a) >> t=1:0.02:5; y=3*exp(-0.5*(t)).*cos(pi*(t).^2); z=1-y; hold on, grid on plot(t,y,'r-') plot(t,z,'g--') title('y(t) & 1-y(t)') xlabel('t')

Exercise J: (a) The function is called plotshift, the content of the plotshift.m file:
function plotshift(tshift) % to plot the y(t-tshift), where tshift is the time shift value t=1:0.02:5; z=3*exp(-0.5*(t)).*cos(pi*(t).^2); y=3*exp(-0.5*(t-tshift)).*cos(pi*(t-tshift).^2); subplot(2,1,1); plot(t,z,'r-'), grid on title('y(t)') subplot(2,1,2); plot(t,y,'g--'), grid on title(['y(t-',num2str(tshift),')']) xlabel('t')

To plot y(t-0.5), to run the function in matlab, >>plotshift(0.5) <enter> The plot:

15

S-ar putea să vă placă și