10guide to matlab-r1

Upload: andreea-novacescu

Post on 03-Apr-2018

212 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 10Guide to MATLAB-r1

    1/15

    1

    A Guide to MATLABRev.10

    Some basic use of MATLAB is introduced, and some exercises are provided at the end of each sectionbelow. You should finish them yourselves, and if necessary, you can check the suggested solution at theend of this document.

    A. HELP facility

    A help facility provides online information for most MATLAB topics. The commandhelp

    it displays a list of directories that contains MATLAB related files as below.HELP topics:

    matlab\general - General purpose commands.

    matlab\ops - Operators and special characters.

    matlab\lang - Programming language constructs.

    matlab\elmat - Elementary matrices and matrix manipulation.

    matlab\elfun - Elementary math functions.

    matlab\specfun - Specialized math functions.matlab\matfun - Matrix functions - numerical linear algebra.

    matlab\datafun - Data analysis and Fourier transforms.

    matlab\polyfun - Interpolation and polynomials.

    matlab\funfun - Function functions and ODE solvers.

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

    Example ,

    Type in help matlab\elfunand press

    A list of commonly usedmath functions show. Take alook on it.

    In the middle of the list, youwill see how a complexnumber is defined.

    Command Window

  • 7/28/2019 10Guide to MATLAB-r1

    2/15

    2

    The listed commands relating complex numbers areabs - 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 commandcomplex,Key in the following in the command line>>help complex

    it returns the following,

    Exercise A:(a). Use help command to see how to use the commandangle .(b). By use of both the commands angle andcomplex, 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.

    COMPLEX Construct complex result from real and imaginary parts.C =COMPLEX(A,B) returns the complex result A +Bi, where A and B areidentically 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 imaginarypart, 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 Aand 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 identicalresults for nonzero B if A and B are double-precision and i or

    j has not been assigned. Use COMPLEX if ambiguity in thevariables "i" or "j" might arise, or if A and B are notdouble-precision, or if B is all zero.

    See also I, J , IMAG, CONJ , ANGLE, ABS, REAL, ISREAL.

  • 7/28/2019 10Guide to MATLAB-r1

    3/15

    3

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

    >> 5+6+7;

    More about the matlab windows:

    Exercise B:

    (a) Compute the value of the function )x3sin(exy x22 = when x = 5.

    All currently defined variableswill be listed out in theWorkspace.

    Workspace

    Command History

    Statements you enter in theCommand Window are loggedin the Command History. Inthe Command History, you canview previously run statements,and copy and execute selectedstatements.

    Command Window

  • 7/28/2019 10Guide to MATLAB-r1

    4/15

    4

    C. Definition of Matrices

    MATLAB is based on matrix and vector algebra; even scalars are treated as 1x1 matrices. Therefore, vectorand 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 7v represents a 1 x 4 vector with elements 1, 3, 5 and 7. Note that commas could have been used in place ofspaces 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 incrementis 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 undefinedintervening elements are set to zero.

  • 7/28/2019 10Guide to MATLAB-r1

    5/15

    5

    You can construct large matrices using small matrices as elements. For example, to attach another row tomatrix A:>> r = [10 11 12];

    >>A=[1 2 3; 4 5 6; 7 8 9]

    A =

    1 2 3

    4 5 6

    7 8 9

    >>A=[A ; r]

    A =

    1 2 3

    4 5 6

    7 8 9

    10 11 12

    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 expressionused 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

    Some examples here,

    Exercises C:

    (a) Construct a matrix A where

    =

    0123

    78910

    8642

    7531

    A

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

  • 7/28/2019 10Guide to MATLAB-r1

    6/15

    6

    D. Getting Workspace Information

    The previous examples have created some variables that are stored in MATLAB workspace. To list thevariables 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 canuse whos.

    E. Matrix Operations

    Transposing MatrixThe special character' (prime or apostrophe) denotes the transpose of matrix.>>B=A'

    B =

    1 4 7

    2 5 8

    3 6 9and>>x=[-1 0 2]'

    x =

    -1

    0

    2

    The prime ' transposes matrices in a formal sense; ifZ is a complex matrix, then Z' is its complex conjugatetransposed. For an unconjugated transpose, use Z.' orconj(Z').

    Adding and Subtracting Matrices

    The symbols + and- denote addition and subtraction of matrices. The operations are defined whenever thematrices have the same dimensions. For example, with the above matrices, A+x is not correct because A is3-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, thescalar is added or subtracted from all elements of the other operand. For example>> y = x -1

    givesy =

    -2

    -1

    1

  • 7/28/2019 10Guide to MATLAB-r1

    7/15

    7

    Multiplying MatricesThe symbol * denotes multiplication of matrices. Matrix-vector products are special cases of generalmatrix-matrix products.For this example A times x,i.e.>>b=A*x

    is allowed and results in the outputb =

    5

    8

    11

    Naturally, a scalar can multiply, or be multiplied by, any matrix:>>2*x

    ans =

    -2

    0

    4

  • 7/28/2019 10Guide to MATLAB-r1

    8/15

    8

    F. Array Operations

    Adding and Subtracting Arrays

    For addition and subtraction, the array operations and the matrix operations are the same, so + and - can beregarded as either matrix or array operations.

    Multiplying and Dividing ArraysThe symbol .* denotes array, or elements-by-elements, multiplication. IfA andB have the samedimensions, then A.*B denotes the array whose elements are simply the products of the individual elementsofA andB.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, xand 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 intime, 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 OperationsSix relational and logical operators are available for comparing two matrices of equal dimensions. Fordetails, type command>>help ops

    Exercise F:

    (a) Generate a vectorx such that

    ]10,,2,1,0[n)n125.0cos(e12)n(xn

    K=

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

  • 7/28/2019 10Guide to MATLAB-r1

    9/15

    9

    G. Control flow

    FOR LoopsMATLAB has its own version of the FOR loop found in computer languages. It allows a statement, orgroup of statements, to be repeated for a fixed or predetermined number of times.The general form for a FOR loop is

    for v = expressionstatements

    endFor example,>>for i = 1:2

    >> for j = 1:3

    >> D(i,j)=i+j;

    >> end

    >>end

    results in

    D = 2 3 4

    3 4 5

    WHILE LoopsThe general form of a WHILE loop is

    while expressionstatements

    end

    IF Loops

    The general form of IF loopsif expressionstatements

    elseif expressionstatements

    elsestatements

    end

    Exercise G:

    (a) Using FOR Loops, generate a 4x4 complex matrix Y whose elements xyjx)y,x(Y 2 = .(b) Using FOR and IF Loops, define a matrix Z whose element is

    >

    =otherwise,0

    3|)y,x(Y|,1)y,x(Z

  • 7/28/2019 10Guide to MATLAB-r1

    10/15

    10

    0 1 2 3 4 5 6 7-1

    -0.8

    -0.6

    -0.4

    -0.2

    0

    0.2

    0.4

    0.6

    0.8

    1x=sin(t),ysin(t)

    t

    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 PlotIf y is vector, plot (y) produces a linear graph of elements of y versus the index of the elements of y. If youspecify 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 asingle call to plot:

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

    The command line :>>plot(t , x , 'r-' , t , y , 'g--' )

    produces a graph ofx versus t andy versus t on the same axes. The first set of data is plotted with a redsolid 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 plotOther useful commands: subplot, plot3 (3D plot), stem, stairs, hist, hold, legend., for example,

    Exercise H:

    (a). Plot y(t) and z(t) on the same graph , for 5 >t >1, such that

    )t(y1)t(z

    )tcos(e3)t(y 2t5.0

    =

    =

  • 7/28/2019 10Guide to MATLAB-r1

    11/15

    11

    I. Scripts

    When you invoke a script (called M-file), MATLAB simply executes all the command lines found in thescript file. Scripts can operate on existing data in the workspace, or they can create new data on which tooperate. Any variables that they create remain in the workspace so you can use them in furthercomputations.

    You are going to create a text file calledtesting.m and store it under D:/matlab/mfiles/, here is the contentof the testing.m file,

    % comment text -- testing.m scriptclear % remove all variables from the workspacex =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.

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

    - Now you can run the testing.m in the matlab command window, in the command window,>> testing

    - Then a stem graph appears, and the variables used (x andy) are shownin the workspace window.

    D:/matlab/mfiles

  • 7/28/2019 10Guide to MATLAB-r1

    12/15

    12

    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 lastsection is simply a file containing a sequence of MATLAB statements). Functions make use of their ownlocal variables and accept input arguments. The M-file name, less its extension, is what MATLAB searchesfor when you try to use the script or function. The name of a function, as defined in the first line of thefunction 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 theirown 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 thatis specified in the MATLAB path list. For example, the M-files to be used are now stored in a directorycalled "D:\matlab\mfiles", in order to access these M-files either change the current working directory toD:\matlab\mfiles or permanently add this directory in MATLAB by clicking on FileSet 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;

    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

    )tcos(e3)t(y 2t5.0 = 5>t>1

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

    two input arguments, x & y

    one output argument

  • 7/28/2019 10Guide to MATLAB-r1

    13/15

    13

    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 3 5 72 4 6 8

    10 9 8 73 2 1 0

    (b)>> A(2:3, 3:4)

    ans =

    6 88 7

    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

  • 7/28/2019 10Guide to MATLAB-r1

    14/15

    14

    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 54 8 12 16 209 18 27 36 45

    16 32 48 64 8025 50 75 100 125

    Exercise G:

    (a)

    >>for x=1:4for y=1:4Y(x,y)=x^2-x*y*j;

    endend

    >> Y

    Y =

    1.0000 - 1.0000i 1.0000 - 2.0000i 1.0000 - 3.0000i 1.0000 - 4.0000i

    4.0000 - 2.0000i 4.0000 - 4.0000i 4.0000 - 6.0000i 4.0000 - 8.0000i9.0000 - 3.0000i 9.0000 - 6.0000i 9.0000 - 9.0000i 9.0000 -12.0000i

    16.0000 - 4.0000i 16.0000 - 8.0000i 16.0000 -12.0000i 16.0000 -16.0000i

    (b)>> for x=1:4

    for y=1:4if abs(Y(x,y)) > 3

    Z(x,y)=1;else

    Z(x,y)=0;end

    endend

    >> Z

    Z =

    0 0 1 11 1 1 11 1 1 11 1 1 1

  • 7/28/2019 10Guide to MATLAB-r1

    15/15

    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 valuet=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 ontitle('y(t)')subplot(2,1,2); plot(t,y,'g--'), grid ontitle(['y(t-',num2str(tshift),')'])

    xlabel('t')

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

    The plot: