MATLAB TUTORIAL

ME3201' W 99

 
P. Y. Li and M. Sukhatankar
updated 1/3/99

This is an evolving document. Please send email to mandys@me.umn.edu or pli@me.umn.edu to report bugs or to give constructive comments.

 

Getting Started with Matlab on IT-Labs machines

Matlab is installed on both the Silicon Graphics (SGI) machines and Window NTs. SGI machines uses a Unix like operating system and NT machines run Window NTs (obviously). There are slight differences in the way you would get into Matlab and write programs for it depending on which opearting system you are using.

You should have preliminary knowledge of starting programs in either Unix systems (i.e. SGI) or NTs. In particular, you need to know how to use a web browser (e.g. Netscape or Internet Explorer)  to open up the tutorial page (e.g. this one http://www.me.umn.edu/courses/me3201/tutorial.html ). On SGI's you should know how to open up "shells" or "command windows", and to use standard text editors like "vi", or "emacs".
 

    Using  Silicon Graphics Machines:

     http://www.itlabs.umn.edu
    machine 1% mkdir me3201_hw0
     (do not type "%") in the shell meant for UNIX commands. Enter that directory by typing
    machine 2% cd me3201_hw0
      in both UNIX shells.

     Type

    machine 3% matlab
     at the UNIX prompt in the shell meant for Matlab. You should see the following:
 
                             < M A T L A B (R) >
                (c) Copyright 1984-98 The MathWorks, Inc.
                            All Rights Reserved
                            Version 5.2.1.1420
                                Apr 30 1998


        ----------------------------------------------------------
                Your MATLAB license will expire in 29 days.
                Please contact your system administrator or
                The MathWorks to renew this license.
        ----------------------------------------------------------


  To get started, type one of these: helpwin, helpdesk, or demo.
  For product information, type tour or visit www.mathworks.com.
 
  • Congratulations ! You are now in the Matlab command environment. You will get a Matlab command prompt >>. To get started, type one of these commands: helpwin, helpdesk, or demo. It is a good idea to go through the Matlab tour (type tour at the >> prompt),  especially, the portions on Basic matrix operations and on matrix manipulation in the "Products - Matlab - Matrices" link sequence. Also try going through "demo" to get another introduction to Matlab.
  • Using Windows NT Machines:


    Starting Matlab in NT can be achieved from the Programs menu (using the mouse and the left key click). You will get a Matlab command window. You should again see the following:

         Help on Matlab is available and you can invoke by typing help now at the Matlab prompt >>.  You will now get a list of help topics displayed like:
              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.
              matlab/sparfun        -  Sparse matrices.
              matlab/graph2d       -  Two dimensional graphs.
              matlab/graph3d       -  Three dimensional graphs.

              Help on individual topics can be obtained by typing the second word in the list.  You can again get help on the subtopics by typing
              help [subtopic].  For example, to get help on Elementary math functions, type "help elfun"

              >> help elfun

              at the Matlab prompt.  To get help on the sine function within this module type

              >> help sin

              Some demos are available in Matlab which you can invoke using demos, demo, tour etc. at the Matlab prompt.

              Type

              >> help ops

              to find out what types of simple operations are available.

        Hints on using Matlab

                   To create a 3x3 matrix A, type in the following program statement

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

                   This results in a 3x3 matrix which looks like

                       A =
                                           1  2  3
                                           4  5  6
                                           7  8  9

                   There are many ways to generate a matrix. You may check the functions 'ones', 'zeros', and 'eye'. Other matrix generation functions     include 'rand', 'compan','hilb', and so on. At the end of this document is a Matlab working tutorial which contains other examples.
     

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

    and

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

    Basically, ";" and "," are both terminators of statements. They differ in that ";" supresses printing the answer whereas "," does not. Use the help facility "help punct" to find out exactly what the differences are.
     

                   >> t = 0:2:6

                   This generates a row vector [0, 2, 4, 6]. (Use "help punct" and "help colon" to learn exactly what it means).

                   elfun
                   funfun
                   graph2d
                     for
                   print
                   plot
                   xlabel
                   ylabel
                   title
                   axis
                   clear all             >> print file_name.

                   This lets you save your file in a postscript file named file_name.ps.  Do not add an extension like .ps to the file name while using the         print command. Postscript files are files that printers understand.

    How to write a 'Good' program:

                1. Always start off your programs with the 'clear all' statement.
                2. Develop a practice of using ample comments and always be sure to use the '%' sign for writing comments. This ensures clarity in your programs and tells the reader in plain English what is going on.
                3. Maintain an uniform and consistent flow of thought when writing your programs. Use an indented style . It makes the programs easier to read, the program syntax is easier to check, and it forces you to think in terms of building your programs in blocks.
                4. Remember that many errors can be removed by simply checking the syntax and ensuring that all variables which are being used are defined.
                5.Remember to note  error messages. Your programs will build on each other. Error messages will help you debug future programs.
                6.In Matlab, try to use built in functions rather than creating loops in your programs. Matlab is optimized to run the built-in functions.
                7.If you are having trouble writing a program, get a small part of it running and try to build on that.
     
     

    MATLAB TUTORIAL

    (taken from the University of Florida, http://www.math.ufl.edu/~frank/complin/fall97/tutorial/tute2.html )

    Acknowledgement. Most of this tutorial is taken from Rick Smith's Matlab Project Notes.

    1. Building Matrices

    Matlab has many types of matrices which are built into the system. Try
    rand(7)
    rand(2,5)
    help rand
    Another special matrix is the Hilbert matrix:
    hilb(5)
    help hilb
    A 5×5 magic square is given by
    magic(5)
    help magic
    Here are some standard matrices from linear algebra:
    eye(6)
    zeros(4,7)
    ones(5)
    You can build matrices several ways. Try
    [1 2 3 5 7 9]
    [1, 2, 3; 4, 5, 6; 7, 8, 9]
    [1 2 (return) 3 4 (return) 5 6]
    Here (return) is the Return or Enter key. Try these:
    [eye(2); zeros(2)]
    [eye(2); zeros(3)]
    Did you get an error message? Why? Now try
    [eye(2), ones(2,3)]

    2. Functions

    a=magic(4)
    a'
    Notice that a' gave the transpose of a. Try these
    3*a
    -a
    a+(-a)
    b=max(a)
    max(b)
    Some functions can return more than one value. The function max will return the maximum value and also the column index where the maximum occurs. Try
    [m,i]=max(b)
    min(a)
    b=2*ones(a)
    a*b
    a
    Usually a dot in front of an operation will change the operation. In the case of multiplication a.*b will give entry-by-entry multiplication instead of the usual matrix multiplication. Try (dont forget the "dot"):
    a.*b
    x=5
    x^2
    a*a
    a^2
    a.^2
    a
    triu(a)
    diag(a)
    diag(diag(a))
    c=rand(4,5)
    size(c)
    [m,n]=size(c)
    m
    d=.5-c
    There are many functions we apply to scales which can also be applied to matrices. Try
    sin(d)
    exp(d)
    log(d)
    abs(d)
    MATLAB has functions to round floating point numbers to integers. The functions are round, fix, ceil, and floor. Try these
    f=[-.5 .1 .5]
    round(f)
    fix(f)
    ceil(f)
    floor(f)
    sum(f)
    prod(f)
     

     
     
     
     
     

    3. Relations and Logical Operations

    In this section you should think of 1 as "true" and 0 as "false". The notations &, |, ~ stand for "and", "or" and "not", respectively. The notation == is a check for equality. Try these
    a=[1, 0, 1, 0]
    b=[1, 1, 0, 0]
    a==b
    a<=b
    ~a
    a&b
    a&~a
    a|b
    a|~a
    The function any is used to determine whether there is a nonzero entry in a vector. The function all determines if all the entries are zero. Try
    a
    any(a)
    all(a)
    c=zeros(1,4)
    d=ones(1,4)
    any(c)
    all(d)
    e=[a', b', c', d']
    any(e)
    all(e)
    any(all(e))
     

     
     
     
     
     

    4. Colon Notation

    MATLAB also offers some very powerful ways for creating vectors and then using this means to tear a matric apart. Try
    x=-2:1
    length(x)
    -2:.5:1
    -2:.2:1
    a=magic(5)
    a(2,3)
    Now we will use the colon notation to get a column of a.
    a(2,:)
    a(:,3)
    a
    a(2:4,:)
    a(:,3:5)
    a(2:4,3:5)
    a(1:2:5,:)
    You can put a vector in the row or column position of a.
    a(:,[1, 2, 5])
    a([2, 5], [2, 4, 5])
    You can also make assignment statements using a vector or a matrix.
    b=magic(5)
    b([1 2],:)=a([1 2],:)
    a(:,[1 2])=b(:,[3 5])
    a(:,[1 5])=a(:,[5 1])
    a=a(:,5:-1:1)
    When you insert a 0-1 vector into the column position, the columns which correspond to the 1's are displayed. Try
    v=[0 1 0 1 1]
    a(:,v)
    a(v,:)
     

     
     
     
     
     

    5. Programming in Matlab

    MATLAB is also a programming languange. Br creating a file with the extension .m you can easily write and run programs. If you were to create a program file myfile.m in the MATLAB language, then you can make the command myfile from MATLAB and it will run like any other MATLAB function. There is no need to compile the program since MATLAB is an interpretative language. Such a file is called a m-file. We will describe the basic programming constructions. These should be enough to enable you to write clear programs.
     
     
     
     

    5.1 Assignment

    Assignment is the method of giving a value to a varaiable. You have already seen this in the interactive mode. We write x=a to give the value of a to x. Here is a short program illustrating the use of assignment.
    function r=mod(a,d)
    
    % r=mod(a,d). If a and d are integers, then r is the integer
    % remainder of a after division by d. If a and d are integer
    % matrices, then r is the matrix of remainders after division
    % by corresponding entries. Compare with MATLAB's rem.
    
    r=a-d.*floor(a./d)
    
    
    
    You should make a file named mod.m and enter this program exactly as it is written. Or you can download it. Now assign some integer values for a and d. Run
     
     
    mod(a,d)
    This should run like any builtin MATLAB function. Type
    help mod
    This should produce the comments that follow the % signs. Now type
    type mod
    This will give a listing of the file.
     
     

    5.2 Branching

    Branching is the construction

    if condition, program end
    Here condition is a MATLAB function and program is a program segment. The entire construction executes the i>program just in case the value of condition is not 0. If that value is 0, the control moves on to the next program construction. You should keep in mind that MATLAB regards a==b and a<=b with values 0 or 1. Below are two more variations.

    if condition,
       program1
    else
       program2
    end
    In this case, if condition is 0, then program2 is executed.

    if condition1,
        program1
      elseif condition2
        program2
      end
    This time if condtion1 is not 0, then program1 is executed. If condition1 is 0 and if condition2 is not 0, then program2 is executed. Otherwise control is passed on to the next construction. Here is a short program to illustrate branching.

    function b=even(n)
    
    % b=even(n). If n is an even integer,
    % then b=1, otherwise b=0.
    
    if mod(n,2)==0,
       b=1;
       else b=0;
    end
     

     
     
     
     
     
     

    5.3 For Loops

    A for loop is a construction of the form

    for i=1:n, program, end
    Here we will repeat program once for each index value i. Below are some sample programs.

    function c=add(a,b)
    
    % c=add(a,b). This is the function
    % which adds the matrices a and b.
    % It duplicates the MATLAB function
    % a+b.
    
    [m,n]=size(a);
    [k,l]=size(b);
    if m~=k | n~=l,
       error('matrices not the same size');
       return,
    end
    c=zeros(m,n)
    for i=1:m,
       for j=1:n,
          c(i,j)=a(i,j)+b(i,j);
       end
    end
    
    
    The next program is matrix multiplication.
    function c=mult(a,b)
    
    % c=mult(a,b). This is the matrix product
    % of the matrices a and b.
    % It duplicates the MATLAB function
    % a*b.
    
    [m,n]=size(a);
    [k,l]=size(b);
    if n~=k,           
       error('matrices are not compatible');
       return,
    end
    c=zeros(m,l)
    for i=1:m,
       for j=1:n,
          for p=1:n,
             c(i,j)=a(i,j)+a(i,p)*b(p,j);
          end
       end
    end
    
    
    Notice how the branch construction was used for error messages.
     
     
     
     
     
     
     

    5.4 While Loops

    A while loop is a construction of the form

    while condition, program, end

    Here condition is a MATLAB functionm, as with the branching construction. The program program will execute successively as long as the vlaue of condition is not 0. Here is a sample program.

    function l=twolog(n)
    
    % l=twolog(n). l is the floor of
    % the base 2 logarithm of n.
    
    l=0;
    m=2;
    while m<=n
       l=l+1;
       m=2*m;
    end
    
    
     

     
     
     
     
     
     

    5.5 Recursion

    Recursion is a devious construction which allows a function to call itself. Here is a simple example:
    function y=twoexp(n)
    
    % y=twoexp(n). This is a recursive program
    % for computing y=2^n. the program halts
    % only if n is a nonnegative integer.
    
    if n==0,
       y=1;
    else
       y=2*twoexp(n-1);
    end
    
    
     

     
     
     
     
     
     

    5.6 Miscellaneous

    It is possible to place a matrix valued function as the condition of a branching construction or while loop. However one must be careful! Consider the construction

    if A~=B, program, end

    You would like program to execute if the matrices A and B differ i some entry. Under the convention, program will only execute when they differ on all entries. There are some ways around this problem. One is the construction

    if A==B, else program, end

    which will pass control to the "else" part if A and B differ on at least one entry. Another solution is to convert A==B into a binary valued functionm by using all(all(A==B)). The inside all creates a binary vector whose ith entry is 1 only if the ith column of A is the same as the ith column of B. The outside all produces a 1 if all the entries of the vector are 1. Thus if A and B differ on at least one entry, then all(all(A==B))=0. The construction

    if ~all(all(A==B))), program, end

    then behaves in the desired way.
     
     
     
     
     
     

    5.7 Scripts

    We have seen m-files which have the function declaration at the top. In practice these files create new MATLAB functions. In creating a function whcih we will call fun(a) we might use a variable like x. Now suppose that the variable x has a value in your session? What happens to the value x after you make a call to fun(a)? Nothing. The only way to change the value of x when running fun is to assign x=fun(a). The x inside the program fun.m behaves independently from the variable x in your session.

    A script is an m-file without a function declaration at the top. A script treats variables differently than a function file. In a script, if x appears in a program, which you might call scrpt, and x has a value in your session, then a call to scrpt might change the value of x. If you do not make that function declaration, then the variables in your session can be altered. Sometimes this is useful but usually it is recommended that you use function files.
     
     
     
     
     
     

    6. Key Words and Symbols (partial list)

    magic round help function ==
    eye floor format short if ~=
    diag abs format long else <
    ones sqrt who elseif <=
    zeros sin clear end >
    rand cos exit while >=
    hilb tan ans return &
    tril asin load = |
    triu acos save ; ~
    sum atan diary : any
    prod exp type % all
    max log dir , +
    min eps     -
    size pi     *
    length sign     .
            '
            '
            /
            ./
            ^
            .^