Introduction to MATLAB by dfsdf224s

VIEWS: 8 PAGES: 26

									       Tutorial #1 (prepared by H.D. Ng)

              Introduction to MATLAB
            1.   Basic functions
            2.   Vectors, matrices, and arithmetic
            3.   Flow Constructs (Loops, If, etc)
            4.   Create M-files
            5.   Plotting
http://users.encs.concordia.ca/~hoing/course.html
                 To get started
• Create a directory reserved for saving files
associated with MATLAB
• After you start the MATLAB program :
 To get started, type one of these: helpwin, helpdesk, or demo.
 For product information, type tour or visit www.mathworks.com.

» cd c:/eddie/                   Change your current directory to the
                                 MATLAB working directory
»
» ls
                          List all your files in this directory
.     ..     method1.m method2.m method3.m
                                                  All the filename
»
                                                  contained in this
                     MATLAB prompt
                                                  directory
                  Basic functions
• MATLAB as a calculator                 +      addition
  » (3+5)/7        Sum of (3+5)          -      subtraction
  ans =            divided by 7          /      division
                                         *      multiplication
    1.1429                               ^      power
  » x = (3+5)/7     define a variable
  x=
                  **MATLAB follows the order operation and works
    1.1429        according to the following priorities:
  »x               1. quantities in brackets
                   2. Power
  x=
                   3. * / working from left to right
    1.1429         4. + - working from left to right

                  ** MATLAB case sensitive
     Basic function (continued)
• If you want to see how many variables you have
  defined so far, you can use the following command:

  » who                    List all the variables in the current
                           MATLAB session
  Your variables are:
  ans     x
                           List all the variables with details
  »
  »whos
   Name        Size     Bytes Class
   ans        1x1       8 double array
   x          1x1       8 double array
  Grand total is 2 elements using 16 bytes
     Basic function (continued)
• Once you have defined some variables:
   » x = -10
   x=                   *Once you have define a value for a
     -10                variable, you can use it to perform
                        algebraic operation
   » y = 5*x
   y=
     -50
   » x = (3+5)/7
   x=
                   *By default, MATLAB displays 4
     1.1429        decimal digit if the value is not an
                   integer
                    Format
• By default, the answer only displays 4 decimal
  places if it is not an integer
• If you want to change the format of the output:

  » format long        Other format for the output:
  » pi
                        format short      (4 decimal places)
  ans =                 format short e   (scientific notation)
    3.14159265358979    format long       (more than 12)
                        format bank       (2 decimal place)
              Special Characters
• In MATLAB, there are some special variables:

  » pi               Value for π
   ans =
     3.1416
   » i, j,
                        Imaginary number by default
   ans =                unless you change them
       0+1.0000i
  ans =
         0+1.0000i
                 Build-in function
• In MATLAB, there are also some standard build-in
  functions
                       •Trigonometric function:
  » z = sin (pi/4)            sin ( )       asin ( )
                              cos ( )       acos ( )
   z=
                              tan ( )       atan ( )
     0.7071
                              ** Angle is in radian
   » q = log (4)
   q=                  •Elementary function:
        1.3863                sqrt ( )         √
                              exp ( )          e
                              log ( )          log
                              log10 ( )        log10
     Defining a vector (Row vector)
• MATLAB is a tool for doing computations with
  vectors & matrices
• Row Vectors:           Name of your vector

  » v1 = [2 3, 3]        Square bracket
   v1 =
    2 3 3             You can use either a space or comma to
                      separate the elements in vector definition
   » length (v1)
   ans =
          3         Tell you the number of elements in your
                    vector
       Defining a vector (Row vector)
• You can perform standard linear algebra operations
  on these vectors
   » v2 = 3*v1             Multiplication by a scalar quantity
   v2 =
       6 9 9               Other vector operations:

   » v3 = [2 2]            - Addition/subtraction of a vector

   v3 =                    -dot product …etc

       2 2
   » v4 = v3+v1
   ??? Undefined function or variable ‘v1’
   »
                       **Row vectors must have the same length
 Defining a vector (Column vector)
• Similar you can also define a column vector
  » c1 = [1;3;2]       Square bracket
   c1 =
                   Use colon or enter the value at the
    1              next line for next row elements
    3
    2
   » c2 = [2
          2
          4]
   c2 =
    2
    2
    4
Defining a vector (Column vector)
• We can convert a row vector into a column vector
  (or vice versa) by taking the transpose which can be
  done by using a single quote ’
   » v4 = c1’
                       Transpose operator
   v4 =
       1 3 2
   »
                      Matrices
• In a similar fashion, you can define a matrix in
  MATLAB by doing the following:
  » a =[5 7 9
                            Element in first row
        1 -3 -7]
  a=
    5 7 9                   Use a semi-colon for next row elements
    1 -3 -7
  » a = [ 5 7 9; 1 -3 -7]
   a=
    5 7 9
    1 -3 -7
• Similarly, for matrix operation, it must follow the basic
  rule of linear algebra, eg. dimensions must agree!
              Element access
• MATLAB IS NOT ZERO INDEXED!
• x               retrieves entire matrix x
• x(1,2)          retrieves element at row 1, col 2
• x(1, 5:10)      retrieves row 1, columns 5 to 10
                  (use colon)
• x(1,:)          retrieves row 1, all columns
• Useful functions:
      size(x)     rows, cols of x
        Other build-in functions
• In MATLAB, there are also some standard build-in
  functions to perform some linear algebra

   •Linear algebra
          diag( )    find diagonal of a square matrix
          eig( )     find the eigenvalue
          inv( )     find the inverse
           …etc
  Some housekeeping commands
• The command save can store all the variables
  defined in the workspace in a binary file
  matlab.mat (default name)

• You can also store individual variable by writing:
     save filename X Y Z
                      You specify a filename

• The command load can restore the workspace from
  the file matlab.mat
• The command clear all remove all variables in the
  current workspace
               Making a M-file
• Filename has an extension .m
• You can use M-file to do 2 things:
      - script file (when you want to do many
                     MATLAB operations at the same
                     time, consisting of a sequence of
                     normal MATLAB statement)
      - function file (to create a function)

• To create a M-file, go to the toolbar of the
  MATLAB command window and from:
      file new M-file
                            Script file               Output
%filename= method1.m              Comment (is not
clear all                         a MATLAB            » method1
x1= (2+4)/5;         Erase all    statement)          y1 =
x2= x1*7;            previously
y1= sqrt(15)                                            3.8730
                     defined variables
y2= exp(5)                                            y2 =
v1 = [x1 x2]                MATLAB statement           148.4132
c1 = [y1;y2];
dot_product = v1*c1           To inhibit echo         v1 =
display('SAY HI!!!!')         (operation not shown)     1.2000     8.4000
                                                      dot_product =
 The filename is called method1.m
 Use the command ls to check if this file is in        1.2513e+003
 your currently working directory                     ans =
                                                      SAY HI!!!!
                           Function file
                                                     output
Indicate that this file is a function M-file
                                               » v = [ 67 89 52 98 30]
       Return value Name of your function *
                                               v=
                           Input argument
function [out] = mean (x)                        67    89     52   98    30
% To calculate the mean or average of          » avg = mean(v)
% a list of number
% X is an array of number                      m=
m = length(x)                                    5
out = sum(x)/m
                                               mean =
                                                67.2000
 *The name of your
 function should be the                        avg =
 same as your m-file
 name                                           67.2000
                 Flow Constructs
 • As you learned from programming, there are times
   when you want your code to make a decision:

• IF block               Conditions
      if (<condition>)          <     less than
              <body>            <=    less and equal then
      elseif                    ==    equal
              <body>            >     greater than
      end
                                <     greater and equal then
                                ~=    not equal
                       If statement
% filename method2.m             Output
if (grade< 55)
   display('fail')              » grade=88
else if(grade>85)               grade =
     display('grade A')
   else                             88
     display('pass')            » method2
   end
   end                          ans =
                                grade A
           # of “if” must be    »
           consistent with #
           of “end”
               Flow Constructs
                      Initial value
• For loop
                           Final value (where you stop the loop)
     for i = 1:10
      <body>
     end

                        Initial value
• For loop
                             Final value (where you stop the loop)
     for i = 1:2:10
      <body>
     end                      Specify the increment
               Flow Constructs
• While loop         condition
      n=0
      while (n <8)
      n=n+1
      end
                             Plotting
                                         9

» x=[4 8 11]                            8.5
                    Plot the data        8
x=                  point and           7.5

     4   8     11   connected them       7


                    by straight line    6.5

» y=[4 5 9]                              6

                                        5.5

y=                  Plot the discrete    5

     4   5     9    data point          4.5

                                         4

» plot (x,y)        indicated by o            4   5   6   7   8   9   10   11




» plot(x,y,’o’)
» axis([0 10 0 10])              Change axis [xmin xmax ymin ymax]
» title(‘experimental data’)
» xlabel(‘x’)                         Labeling
» ylabel(‘y’)
» grid on                 Turn on the gird on the graph
                Plotting (continued)
»z                  If the data is stored
                    in a matrix
z=
  4     4
  8     5
  11    9
» plot (z(:,1),z(:,2))


     All row             All row elements
     elements in         in second
     first column        column
                                            Multiple plot on the same
» plot (x1, y1, x2, y2, x3, y3 )
                                            graph (3 set of data points)
                   Plotting (continued)
To make a graph of y = sin(t) on the interval t = 0 to t = 10

   » t = 0:.3:10;
   » y = sin(t);
   » plot(t,y,’r’) ;


  We can also use the
  commant fplot:
   » fplot (‘ff’, [ 0 10])

                                    Limit for x value
Function defined by a m-file
(make sure you put the quotation)

								
To top