52
A BRIEF LIST OF MATLAB COMMANDS Some Basic Commands (Note command syntax is case-sensitive!) matlab loads the program matlab into your workspace. quit quits matlab, returning you to the operating system. exit same as quit. who lists all of the variables in your matlab workspace. whos list the variables and describes their matrix size. clear deletes all matrices from active workspace. clear x deletes the matrix x from active workspace. ... the ellipsis defining a line continuation is three successive periods. save saves all the matrices defined in the current session into the file, matlab.mat. load loads contents of matlab.mat into current workspace. save filename saves the contents of workspace into filename.mat save filename x y z saves the matrices x, y and z into the file titled filename.mat. load filename loads the contents of filename into current workspace; the file can be a binary (.mat) file or an ASCII file. ! the ! preceding any unix command causes the unix command to be executed from matlab. Commands Useful in Plotting. plot(x,y) creates an Cartesian plot of the vectors x & y. plot(y) creates a plot of y vs. the numerical values of the elements in the y-vector. semilogx(x,y) plots log(x) vs y. semilogy(x,y) plots x vs log(y) loglog(x,y) plots log(x) vs log(y). grid creates a grid on the graphics plot. title('text') places a title at top of graphics plot. xlabel('text') writes 'text' beneath the x-axis of a plot. ylabel('text') writes 'text' beside the y-axis of a plot. text(x,y,'text') writes 'text' at the location (x,y) . text(x,y,'text','sc') writes 'text' at point x,y assuming lower left corner is (0,0) and upper right corner is (1,1). gtext('text') writes text according to placement of mouse hold on maintains the current plot in the graphics window while executing subsequent plotting commands. hold off turns OFF the 'hold on' option.

A Brief List of Matlab Commands

Embed Size (px)

Citation preview

Page 1: A Brief List of Matlab Commands

               A BRIEF LIST OF MATLAB COMMANDS Some Basic Commands (Note command syntax is case-sensitive!)      matlab    loads the program matlab into your workspace.     quit      quits matlab, returning you to the operating system.     exit      same as quit.     who       lists all of the variables in your matlab workspace.     whos      list the variables and describes their matrix size.     clear     deletes all matrices from active workspace.     clear x   deletes the matrix  x  from active workspace.     ...       the ellipsis defining a line continuation is three               successive periods.     save      saves all the matrices defined in the current                    session into the file, matlab.mat.     load      loads contents of matlab.mat into current workspace.     save filename  saves the contents of workspace into                     filename.mat     save filename x y z               saves the matrices x, y and z into the file titled               filename.mat.     load filename  loads the contents of filename into current                    workspace; the file can be a binary (.mat) file                    or an ASCII file.     !         the ! preceding any unix command causes the unix               command to be executed from matlab. Commands Useful in Plotting.      plot(x,y) creates an Cartesian plot of the vectors x & y.     plot(y)   creates a plot of y vs. the numerical values of the               elements in the y-vector.     semilogx(x,y) plots log(x) vs y.     semilogy(x,y)  plots x vs log(y)     loglog(x,y)    plots log(x) vs log(y).     grid      creates a grid on the graphics plot.     title('text')  places a title at top of graphics plot.     xlabel('text') writes 'text' beneath the x-axis of a plot.     ylabel('text') writes 'text' beside the y-axis of a plot.     text(x,y,'text')    writes 'text' at the location (x,y) .     text(x,y,'text','sc') writes 'text' at point x,y assuming                         lower left corner is (0,0) and upper                         right corner is (1,1).     gtext('text') writes text according to placement of mouse     hold on   maintains the current plot in the graphics window               while executing subsequent plotting     commands.     hold off  turns OFF the 'hold on' option.     polar(theta,r) creates a polar plot of the vectors r & theta                    where theta is in radians.     bar(x)    creates a bar graph of the vector x. (Note also               the command stairs(y).)      bar(x,y)  creates a bar-graph of the elements of the vector y,               locating the bars according to the vector elements               of 'x'. (Note also the command stairs(x,y).)     hist(x)   creates a histogram. This differs from the bargraph               in that frequency is plotted on the vertical axis.

Page 2: A Brief List of Matlab Commands

     mesh(z)   creates a surface in xyz space where z is a matrix               of the values of the function z(x,y). z can be               interpreted to be the height of the surface above               some xy reference plane.     surf(z)   similar to mesh(z), only surface elements depict               the surface rather than a mesh grid.     contour(z)     draws a contour map in xy space of the function                    or surface z.     meshc(z)  draws the surface z with a contour plot beneath it.     meshgrid  [X,Y]=meshgrid(x,y) transforms the domain specified               by vectors x and y into arrays X and Y that can be               used in evaluating functions for 3D mesh/surf plots.     print     sends the contents of graphics window to printer.     print filename -dps      writes the contents of current               graphics to 'filename' in postscript format.  Equation Fitting      polyfit(x,y,n) returns the coefficients of the n-degree          polynomial for the vectors x and y. n must be at least 1          larger than the length of the vectors x and y. If n+1 =          length(x) the result is an interpolating polynomial. If          n+1 > length(x) the result is a least-squares polynomial          fit. The coefficients are stored in order with that of          the highest order term first and the lowest order last.     polyval(c,x)   calculates the values of the polynomial whose          coefficients are stored in  c, calculating for every          value of the vector x. Data Analysis Commands      max(x)    returns the maximum value of the elements in a               vector or if x is a matrix, returns a row vector               whose elements are the maximum values from each               respective column of the matrix.     min (x)   returns the minimum of x (see max(x) for details).     mean(x)   returns the mean value of the elements of a vector               or if x is a matrix, returns a row vector whose               elements are the mean value of the elements from               each column of the matrix.     median(x) same as mean(x), only returns the median value.     sum(x)    returns the sum of the elements of a vector or if x               is a matrix, returns the sum of the elements from               each respective column of the matrix.     prod(x)   same as sum(x), only returns the product of               elements.     std(x)    returns the standard deviation of the elements of a               vector or if x is a matrix, a row vector whose               elements are the standard deviations of each               column of the matrix.     sort(x)   sorts the values in the vector x or the columns of               a matrix and places them in ascending order. Note               that this command will destroy any association that               may exist between the elements in a row of matrix x.     hist(x)   plots a histogram of the elements of vector, x. Ten               bins are scaled based on the max and min values.

Page 3: A Brief List of Matlab Commands

     hist(x,n) plots a histogram with 'n' bins scaled between the               max and min values of the elements.     hist((x(:,2))  plots a histogram of the elements of the 2nd                    column from the matrix x.     fliplr(x) reverses the order of a vector. If x is a matrix,               this reverse the order of the columns in the matrix.     flipud(x) reverses the order of a matrix in the sense of               exchanging or reversing the order of the matrix               rows. This will not reverse a row vector!     reshape(A,m,n)      reshapes the matrix A into an mxn matrix               from element (1,1) working column-wise. SPECIAL MATRICES      zeros(n)  creates an nxn matrix whose elements are zero.     zeros(m,n)   creates a  m-row, n-column matrix of zeros.     ones(n)   creates a n x n square matrix whose elements are 1's     ones(m,n)' creates a mxn matrix whose elements are 1's.     ones(A)   creates an m x n matrix of 1's, where m and n are                based on the size of an existing matrix, A.      zeros(A)  creates an mxn matrix of 0's, where m and n are               based on the size of the existing matrix, A.     eye(n)    creates the nxn identity matrix with 1's on the               diagonal. Miscellaneous Commands      length(x) returns the number elements in a vector.     size(x)   returns the size m(rows) and n(columns) of matrix x.     rand      returns a random number between 0 and 1.     randn     returns a random number selected from a normal               distribution with a mean of 0 and variance of 1.     rand(A)   returns a matrix of size A of random numbers.        ALGEBRAIC OPERATIONS IN MATLAB Scalar Calculations.                          +         addition                                -         subtraction                         *         multiplication                         /         right division (a/b means a ÷ b)                         \         left division  (a\b means b ÷ a)                         ^         exponentiation   The precedence or order of the calculations included in a singleline of code follows the below order:          Precedence                Operation               1         parentheses

Page 4: A Brief List of Matlab Commands

               2         exponentiation, left to right               3         multiplication and division, left  right               4         addition and subtraction, left  right MATRIX ALGEBRA     In matrix multiplication, the elements of the product, C, oftwo matrices A*B is calculated from           Cij = ‘ (Aik * Bkj)   {summation over the double index k} To form this sum, the number of columns of the first or left matrix(A) must be equal to the number of rows in the second or rightmatrix (B). The resulting product, matrix C, has an order for whichthe number of rows equals the number of rows of the first (left)matrix (A) and the product (C) has a number of columns equal to thenumber of columns in the second (right) matrix (B). It is clearthat A*B IS NOT NECESSARILY EQUAL TO B*A!       The PRODUCT OF A SCALAR AND A MATRIX is a matrix in whichevery element of the matrix has been multiplied by the scalar.  ARRAY PRODUCTS      Sometimes it is desired to simply multiply or divide eachelement of an matrix by the corresponding element of anothermatrix. These are called 'array operations" in 'matlab'. Array orelement-by-element operations are executed when the operator ispreceded by a '.' (period). Thus      a .* b    multiplies each element of a by the respective               element of b     a ./ b    divides each element of a by the respective element               of b     a .\ b    divides each element of b by the respective element               of a     a .^ b    raise each element of a by the respective b element     TRANSPOSE OF A MATRIX      x'        The transpose of a matrix is obtained by               interchanging the rows and columns. The 'matlab'               operator that creates the transpose is the single               quotation mark, '. INNER PRODUCT OF TWO VECTORS      The inner product of two row vectors G1 and G2 is G1*G2'.     The inner product of two column vectors H and J is H'*J.  OUTER PRODUCT OF TWO VECTORS      If two row vectors exist, G1 and G2, the outer product issimply      G1' * G2       {Note G1' is nx1 and G2 is 1xn} 

Page 5: A Brief List of Matlab Commands

and the result is a square matrix in contrast to the scalar resultfor the inner product. DON'T CONFUSE THE OUTER PRODUCT WITH THEVECTOR PRODUCT IN MECHANICS! If the two vectors are column vectors,the outer product must be formed by the product of one vector timesthe transpose of the second!   SOLUTION TO SIMULTANEOUS EQUATIONS      Using the Matrix Inverse      inv(a)    returns the inverse of the matrix  a.               If ax=b is a matrix equation and  a  is the               coefficient matrix, the solution  x  is  x=inv(a)*b.      Using Back Substitution      a\b       returns a column vector solution for the matrix               equation  ax=b where a is a coefficient matrix.     b/a       returns a row vector solution for the matrix               equation  xa=b where a is a coefficient matrix. Some basic commands you will need:      matlab    loads the program matlab into your workspace     quit      quits matlab, returning you to the operating system     exit      same as quit     who       lists all of the variables in your matlab workspace     whos      list the variables and describes their matrix size NOTE - When using the workstations, clicking on UP ARROW willrecall previous commands. If you make a mistake, the DELETE key ORthe backspace key may be used to correct the error; however, one ofthese two keys may be inoperable on particular systems.      'matlab' uses variables that are defined to be matrices. Amatrix is a collection of numerical values that are organized intoa specific configuration of rows and columns. The number of rowsand columns can be any number, for example, 3 rows and 4 columnsdefine a 3 x 4 matrix which has 12 elements in total. A scalar isrepresented by a 1 x 1 matrix in matlab. A vector of n dimensionsor elements can be represented by a n x 1 matrix, in which case itis called a column vector, or a vector can be represented by a 1 xn matrix, in which case it is called a row vector of n elements.The matrix name can be any group of letters and numbers up to 19,but always beginning with a letter. Thus 'x1' can be a variablename, but '1x' is illegal. 'supercalafragilesticexpealladotious'can be a variable name; however, only the first 19 characters willbe stored! Understand that 'matlab' is "case sensitive", that is,it treats the name 'C' and 'c' as two different variables.Similarly, 'MID' and 'Mid' are treated as two different variables.Here are examples of matrices that could be defined in 'matlab'.Note that the set of numerical values or elements of the matrix arebounded by brackets ......[  ].  

Page 6: A Brief List of Matlab Commands

     c = 5.66  or   c = [5.66]          c is a scalar or                                        a 1 x 1 matrix      x = [ 3.5, 33.22, 24.5 ]           x is a row vector or                                        1 x 3 matrix      x1 = [ 2                           x1 is column vector or            5                           4 x 1 matrix            3           -1]      A = [ 1  2  4                      A is a 4 x 3 matrix           2 -2  2           0  3  5           5  4  9 ]  An individual element of a matrix can be specified with thenotation A(i,j) or Ai,j for the generalized element, or by A(4,1)=5for a specific element. When  'matlab' prints a matrix on the monitor, it will be organizedaccording to the size specification of the matrix, with each rowappearing on a unique row of the monitor screen and with eachcolumn aligned vertically and right-justified.  The numerical values that are assigned to the individual elementsof a matrix can be entered into the variable assignment in a numberof ways. The simplest way is by direct keyboard entry; however,large data sets may be more conveniently entered through the use ofstored files or by generating the element values using matlabexpressions. First, we will look at the use of the keyboard fordirect entry.   KEYBOARD DEFINITION OR ENTRY FOR A MATRIX A matrix can be defined by a number of matlab expressions. Examplesare listed below for a 1 x 3 row vector, x, whose elements are x(1) = 2, x(2) = 4 and x(3) = -1.      x = [ 2  4  -1 ]    or  x=[2 4 -1]    or     x = [ 2,4,-1 ] (A keystroke 'enter' follows each  of the above matlab statements.)Notice that brackets must be used to open and close the set ofnumbers, and notice that commas or blanks may be used as delimitersbetween the fields defining the elements of the matrix. Blanks usedaround the = sign and the brackets are superfluous; however, theysometimes make the statement more readable. A 2x4 matrix, y, whose elements are y(1,1)=0, y(1,2) = y(1,3) = 2,y(1,4) = 3, y(2,1) = 5, y(2,2) = -3, y(2,3) = 6 and y(2,4) = 4 canbe defined      y = [ 0 2 2 3                  5 -3 6 4 ]    or     y = [ 0 2 2 3 ; 5 -3 6 4 ]

Page 7: A Brief List of Matlab Commands

 The semicolon ";" is used to differentiate the matrix rows whenthey appear on a single line for data entry. The elements of a matrix can be defined with algebraic expressionsplaced at the appropriate location of the element. Thus      a = [ sin(pi/2) sqrt(2) 3+4 6/3 exp(2) ]      defines the matrix      a = [ 1.0000  1.4142  7.0000  2.0000  7.3891 ] A matrix can be defined by augmenting previously defined matrices.Recalling the matrix, x, defined earlier      x1 = [ x 5 8 ] creates the result      x1 = [ 2  4  -1  5  8 ] The expression       x(5) = 8 creates      x = [ 2 4 -1 0 8 ] Notice that the value "0" is substituted for x(4) which has notbeen explicitly defined. Recalling the definition of matrix, y, above, the expressions      c = [ 4  5  6  3 ]     z = [ y;c ] creates      z = [ 0  2  2  3           5 -3  6  4           4  5  6  3 ] Note that every time a matrix is defined and an 'enter' keystrokeis executed, matlab echoes back the result. TO CANCEL THIS ECHO,THE MATLAB COMMAND LINE CAN INCLUDE A SEMICOLON AT THE END OF THELINE BEFORE THE KEYSTROKE 'ENTER'.      z = [ y ; c ] ; LINE CONTINUATION Occasionally, a line is so long that it can not be  expressed inthe 80 spaces available on a line, in which case a linecontinuation is needed. In matlab, the ellipsis defining a linecontinuation is three successive periods, as in  "...".  Thus       4 +  5  +  3 ...

Page 8: A Brief List of Matlab Commands

          +  1  +  10  +  2 ...           + 5 gives the result         ans = 30 Notice that in this simple arithmetic operation, no matrix wasdefined. When such an operation is executed in matlab, the resultis assigned to the matrix titled "ans". A subsequent operationwithout an assignment to a specific matrix name will replace theresults in 'ans' by the result of the next operation. In the above,'ans' is a 1x1 matrix, but it need not be so in general. BEFORE YOU QUIT THIS SESSION !!!!! If this is your first lesson using matlab, execute the matlabcommands 'who' and whos' before you 'quit'. Note that each of thesecommands lists the matrices you have defined in this session on thecomputer. The command 'whos' also tells you the properties of eachmatrix, including the number of elements, the row and column size(row x column) and whether the elements are complex or real. IMPORTANT!  If you execute the matlab command 'save' before youquit, all of the matrices that have been defined will be saved ina file titled matlab.mat stored in your workspace.  Should youdesire to save specific matrices during any session, the command'save' followed by the name of the matrix can be executed.  Moredetail on how to save and recall your matrices is discussed in Lesson 2.  PRACTICE PROBLEMS Determine the size and result for the following matrices. Subsequently, carry out the operations on matlab that define thematrices, and check your results using the 'whos' statement. 1.  a = [1,0,0,0,0,1] 2.  b = [2;4;6;10] 3.  c = [5  3  5; 6  2  -3] 4.  d= [3  4        5  7        9   10 ] 5.  e = [3  5  10  0;  0  0 ...              0  3;  3  9  9  8  ] 6.  t = [4  24  9]    q = [t 0 t] 7.  x = [ 3  6 ]    y = [d;x]    z = [x;d]

Page 9: A Brief List of Matlab Commands

 8.  r = [ c; x,5] 9.  v = [ c(2,1); b ] 10.  a(2,1) = -3 (NOTE: Recall matrix "a" was defined in (1)                    above.)New commands in this lesson:      save      saves all the matrices defined in the current               session into the file, matlab.mat, located in               the directory from which you executed matlab.      load      loads contents of matlab.mat into current workspace          save filename x y z               save the matrices x, y and z into the file titled               filename.mat.      load filename  loads the contents of filename into current                    workspace; the file can be a binary (.mat) file                    or an ASCII file.      clear x   erases the matrix 'x' from your workspace      clear     erases ALL matrices from your workspace NOTE - When using PROMATLAB on a workstation, files are stored inthe directory from which you invoked the 'matlab' command.  Whenusing the workstation, create a matlab subdirectory titled 'matlab'or some similar name.  Thereafter, store all files and conduct allmatlab sessions in that subdirectory. ASCII FILES An ASCII file is a file containing characters in ASCII format, aformat that is independent of 'matlab' or any other executableprogram.  Using ASCII format, you can build a file using a screeneditor or a wordprocessing program, for example, that can be readand understood by 'matlab'.  The file can be read into 'matlab'using the "load" command described above. Using a text editor or using a wordprocessor that is capable ofwriting a file in ASCII format, you simply prepare a matrix filefor which EACH ROW OF THE MATRIX IS A UNIQUE LINE IN THE FILE, withthe elements in the row separated by blanks. An example is the 3 x3 matrix           2  3  6          3 -1  0          7  0 -2 If these elements are formatted as described above and stored in afilename titled, for example, x.dat, the 3 x 3 matrix 'x' can beloaded into 'matlab' by the command       load x.dat

Page 10: A Brief List of Matlab Commands

 Open the Text Editor window on your workstation.  Build a 3x3matrix in the editor that follows the format explained above. Store this in your matlab directory using the command      save ~/matlab/x.dat The suffix, .dat, is not necessary; however, it is stronglyrecommended here to distinguish the file from other data files,such as the .mat files which will be described below.  Of course ifyou define the file with the .dat or any other suffix, you must usethat suffix when downloading the file to 'matlab' with the 'load'command.  Remember, the file must be stored in the directory inwhich you are executing matlab.  In the above example, it isassumed that this directory is titled 'matlab'.       Now go to a window in which matlab is opened.  We desire toload the matrix x into matlab.  We might wonder if the file x.datis actually stored in our matlab directory.  To review what filesare stored therein, the unix command 'ls' can be evoked in matlabby preceding the command with an exclamation mark, ! .  Type thecommand      ! ls Matlab will list all of the files in your directory.  You shouldfind one titled "x.dat".   Now, type the command      load x.dat The 3x3 matrix defined above is now down-loaded into your workingspace in matlab.  To ensure that is so, check your variables bytyping 'who' or 'whos'.  FILES BUILT BY MATLAB....THE .mat FILE If at any time during a matlab session you wish to store a matrixthat has been defined in the workspace, the command      save filename will create a file in your directory that is titled filename.mat.The file will be in binary format, understandable only by the'matlab' program.  Note that 'matlab' appends the .mat suffix andthis can be omitted by the user when describing the filename. If the matrix 'x' has been defined in the workspace, it can bestored in your directory in binary matlab format with the command      save x  The filename need not be the same as the matrix name. The filenamed, for example, 'stuff' can be a file that contains the matrix'x'.  Any number of matrices can be stored under the filename. Thusthe command string

Page 11: A Brief List of Matlab Commands

      save stuff x  y  z will store the matrices x, y and z in the file titled 'stuff'.  Thefile will automatically have the suffix  .mat  added to thefilename.  If, during a session, you type the command 'save' withno other string, all of the current matrices defined in yourworkspace will be stored in the file 'matlab.mat'. The load command when applied to  .mat  files follows the sameformat as discussed above for ASCII files; however, you can omitthe file suffix '.mat' when loading  .mat  files to your workspace. COLON OPERATOR The colon operator ' : ' is understood by 'matlab' to performspecial and useful operations. If two integer numbers are separatedby a colon, 'matlab' will generate all of the integers betweenthese two integers.      a = 1:8 generates the row vector,  a = [ 1 2 3 4 5 6 7 8 ]. If three numbers, integer or non-integer, are separated by twocolons, the middle number is interpreted to be a "range" and thefirst and third are interpreted to be "limits". Thus      b = 0.0 : .2 : 1.0 generates the row vector   b = [ 0.0  .2  .4  .6  .8  1.0 ] The colon operator can be used to create a vector from a matrix.Thus if       x = [ 2  6  8           0  1  7          -2  5 -6 ] The command      y = x(:,1)  creates the column vector      y = [  2             0           -2  ] and               yy = x(:,2) creates               yy = [ 6                        1                      5 ] 

Page 12: A Brief List of Matlab Commands

The command      z = x(1,:) creates the row vector      z = [ 2  6  8 ] The colon operator is useful in extracting smaller matrices fromlarger matrices. If the 4 x 3 matrix c is defined by      c = [ -1  0  0            1  1  0            1 -1  0            0  0  2 ]Then       d1 = c(:,2:3) creates a matrix for which all elements of the rows from the 2ndand third columns are used. The result is a 4 x 2 matrix       d1 = [  0  0             1  0            -1  0             0  2 ] The command            d2 = c(3:4,1:2) creates a 2 x 2 matrix in which the rows are defined by the 3rd and4th row of c and the columns are defined by the 1st and 2nd columnsof the matrix, c.      d2 = [ 1  -1              0   0 ] USING THE CLEAR COMMANDS Before quitting this session of 'matlab', note the use of thecommands 'clear' and 'clc'. Note that 'clc' simply clears thescreen, but does not clear or erase any matrices that have beendefined. The command 'clear' erase or removes matrices from yourworkspace. Use this command with care. NOTE THE COMMAND 'CLEAR'WITHOUT ANY MODIFYING STRING WILL ERASE ALL MATRICES IN YOURWORKSPACE. PROBLEMS Define the 5 x 4 matrix, g.      g = [ 0.6  1.5  2.3 -0.5           8.2  0.5 -0.1 -2.0           5.7  8.2  9.0  1.5           0.5  0.5  2.4  0.5

Page 13: A Brief List of Matlab Commands

           1.2 -2.3 -4.5  0.5 ] Determine the content and size of the following matrices and checkyour results for content and size using 'matlab'. 1.  a = g(:,2) 2.  b = g(4,:) 3.  c = [10:15] 4.  d = [4:9;1:6] 5.  e = [-5,5] 6.  f= [1.0:-.2:0.0] 7.  t1 = g(4:5,1:3) 8.  t2 = g(1:2:5,:)New commands in this lesson:      plot(x,y) creates a Cartesian plot of the vectors x & y      plot(y)   creates a plot of y vs. the numerical values of the               elements in the y-vector.      semilogx(x,y) plots log(x) vs y      semilogy(x,y)  plots x vs log(y)      loglog(x,y)    plots log(x) vs log(y)      grid      creates a grid on the graphics plot      title('text')  places a title at top of graphics plot      xlabel('text') writes 'text' beneath the x-axis of a plot      ylabel('text') writes 'text' beside the y-axis of a plot      text(x,y,'text')    writes 'text' at the location (x,y)       text(x,y,'text','sc') writes 'text' at point x,y assuming                         lower left corner is (0,0) and upper                         right corner is (1,1).      polar(theta,r) creates a polar plot of the vectors r & theta                    where theta is in radians.      bar(x)    creates a bar graph of the vector x. (Note also               the command stairs(x).)      bar(x,y)  creates a bar-graph of the elements of the vector y,               locating the bars according to the vector elements               of 'x'. (Note also the command stairs(x,y).) 

Page 14: A Brief List of Matlab Commands

  CARTESIAN OR X-Y PLOTS      One of 'matlab' most powerful features is the ability tocreate graphic plots. Here we introduce the elementary ideas forsimply presenting a graphic plot of two vectors. More complicatedand powerful ideas with graphics can be found in the 'matlab'documentation.      A Cartesian or orthogonal x,y plot is based on plotting thex,y data pairs from the specified vectors. Clearly, the vectors xand y must have the same number of elements. Imagine that you wishto plot the function ex for values of x from 0 to 2.x = 0:.1:2;y = exp(x);plot(x,y) NOTE: The use of selected functions such as exp() and sin() will beused in these tutorials without explanation if they take on anunambiguous meaning consistent with past experience. Here it isobserved that operating on a matrix with these functions simplycreates a matrix in which the elements are based on applying thefunction to each corresponding element of the argument.      Of course the symbols x,y are arbitrary. If we wanted to plottemperature on the ordinate and time on the abscissa, and vectorsfor temperature and time were loaded in 'matlab', the command wouldbe      plot(time,temperature) Notice that the command  plot(x,y)  opens a graphics window. If younow execute the command 'grid', the graphics window is redrawn.(Note you move the cursor to the command window before typing newcommands.) To avoid redrawing the window, you may use the linecontinuation ellipsis. Considerplot(x,y),...grid,...title('Exponential Function'),...xlabel('x'),...ylabel('exp(x)'),text(.6,.4,' y = exp(x)','sc') Note that if you make a mistake in typing a series of lines ofcode, such as the above, the  use of line continuation can befrustrating. In a future lesson, we will learn how to create batchfiles (called '.m' files) for executing a series of 'matlab'commands. This approach gives you better opportunity to return tothe command string and edit errors that have been created.      Having defined the vectors x and y, construct semilog and log-log plots using these or other vectors you may wish to create. Notein particular what occurs when a logarithmic scale is selected fora vector that has negative or zero elements. Here, the vector x hasa zero element (x(1)=0). The logarithm of zero or any negativenumber is undefined and the x,y data pair for which a zero or

Page 15: A Brief List of Matlab Commands

negative number occurs is discarded and a warning message provided.      Try the commands plot(x) and plot(y) to ensure you understandhow they differ from plot(x,y).      Notice that 'matlab' draws a straight line between the data-pairs. If you desire to see a relatively smooth curve drawn for arapidly changing function, you must include a number of datapoints. For example, consider the trigonometric function, sin(x1)(x1 is selected as the argument here to distinguish it from thevector 'x' that was defined earlier. )      Plot sin(x1) over the limits 0 <= x1 <= pi. First define x1with 5 elements, x1 = 0 : pi/4 : piy1 = sin(x1)plot(x1,y1) Now, repeat this after defining a new vector for x1 and y1 with 21elements. (Note the use of the semicolon here to prevent theprinting and scrolling on the monitor screen of a vector or matrixwith a large number of elements!)x1 = 0 : .05*pi : pi ;y1 =sin(x1);plot(x1,y1)  POLAR PLOTS      Polar plots are constructed much the same way as are Cartesianx-y plots; however, the arguments are the angle 'theta' in radiansmeasured CCW from the horizontal (positive-x) axis, and the lengthof the radius vector extended from the origin along this angle.Polar plots do not allow the labeling of axes; however, notice thatthe scale for the radius vector is presented along the vertical andwhen the 'grid' command is used the angles-grid is presented in 15-degree segments. The 'title' command and the 'text' commands arefunctional with polar plots.angle = 0:.1*pi:3*pi;radius = exp(angle/20);polar(angle,radius),...title('An Example Polar Plot'),...grid Note that the angles may exceed one revolution of 2*pi.   BAR GRAPHS      To observe how 'matlab' creates a bargraph, return to thevectors x,y that were defined earlier. Create bar and stair graphsusing these or other vectors you may define. Of course the 'title'and 'text' commands can be used with bar and stair graphs.      bar(x,y) and bar(y)     stair (x,y) and stair(y) 

Page 16: A Brief List of Matlab Commands

  MULTIPLE PLOTS      More than a single graph can be presented on one graphic plot.One common way to accomplish this is hold the graphics window openwith the 'hold' command and execute a subsequent plotting command. x1=0:.05*pi:pi;y1=sin(x1);plot(x1,y1)holdy2=cos(x1);plot(x1,y2) The "hold" command will remain active until you turn it off withthe command 'hold off'.       You can create multiple graphs by using multiple arguments. In addition to the vectors x,y created earlier, create the vectorsa,b and plot both vector sets simultaneously as follows.a = 1 : .1 : 3;b = 10*exp(-a);plot(x,y,a,b)      Multiple plots can be accomplished also by using matricesrather than simple vectors in the argument.  If the arguments ofthe 'plot' command are matrices, the COLUMNS of y are plotted onthe ordinate against the COLUMNS of x on the abscissa. Note that xand y must be of the same order! If y  is a matrix and x is avector, the rows or columns of y are plotted against the elementsof x. In this instance, the number of rows OR columns in the matrixmust correspond to the number of elements in 'x'. The matrix 'x'can be a row or a column vector!      Recall the row vectors 'x' and 'y' defined earlier. Augmentthe row vector 'y' to create the 2-row matrix, yy.yy=[y;exp(1.2*x)];plot(x,yy)   PLOTTING DATA POINTS & OTHER FANCY STUFF      Matlab connects a straight line between the data pairsdescribed by the vectors used in the 'print' command.  You may wishto present data points and omit any connecting lines between thesepoints.  Data points can be described by a variety of characters ( . , + , * , o and  x .) The following command plots the x,y dataas a "curve" of connected straight lines and in addition places an'o' character at each of the x1,y1 data pairs. plot(x,y,x1,y1,'o')      Lines can be colored and they can be broken to makedistinctions among more than one line. Colored lines are effectiveon the color monitor and color printers or plotters.  Colors areuseless on the common printers used on this network.  Colors are

Page 17: A Brief List of Matlab Commands

denoted in 'matlab' by the symbols r(red), g(green), b(blue),w(white) and i(invisible).  The following command plots the x,ydata in red solid line and the r,s data in broken green line.      plot(x,y,'r',r,s,'--g') PRINTING GRAPHIC PLOTS      Executing the 'print' command will send the contents of thecurrent graphics widow to the local printer.        You may wish to save in a graphics file, a plot you havecreated.  To do so, simply append to the 'print' command the nameof the file.  The command      print filename will store the contents of the graphics window in the file titled'filename.ps' in a format called postscript.  You need not includethe  .ps  suffix, as matlab will do this.  When you list the filesin your matlab directory, it is convenient to identify any graphicsfiles by simply looking for the files with the  .ps  suffix.  Ifyou desire to print one of these postscript files, you canconveniently "drag and drop" the file from the file-manager windowinto the printer icon.Commands introduced in this lesson:      max(x)    returns the maximum value of the elements in a               vector or if x is a matrix, returns a row vector               whose elements are the maximum values from each               respective column of the matrix.      min (x)   returns the minimum of x (see max(x) for details).      mean(x)   returns the mean value of the elements of a vector               or if x is a matrix, returns a row vector whose               elements are the mean value of the elements from               each column of the matrix.          median(x) same as mean(x), only returns the median value.      sum(x)    returns the sum of the elements of a vector or if x               is a matrix, returns the sum of the elements from               each respective column of the matrix.      prod(x)   same as sum(x), only returns the product of               elements.      std(x)    returns the standard deviation of the elements of a               vector or if x is a matrix, a row vector whose               elements are the standard deviations of each               column of the matrix.      sort(x)   sorts the values in the vector x or the columns of               a matrix and places them in ascending order. Note               that this command will destroy any association that               may exist between the elements in a row of matrix x.

Page 18: A Brief List of Matlab Commands

      hist(x)   plots a histogram of the elements of vector, x. Ten               bins are scaled based on the max and min values.      hist(x,n) plots a histogram with 'n' bins scaled between the               max and min values of the elements.      hist((x(:,2))  plots a histogram of the elements of the 2nd                    column from the matrix x.      The 'matlab' commands introduced in this lesson  performsimple statistical calculations that are mostly self-explanatory.A simple series of examples are illustrated below. Note that'matlab' treats each COLUMN OF A MATRIX as a unique set of "data",however, vectors can be row or column format.  Begin the exerciseby creating a 12x3 matrix that represents a time history of twostochastic temperature measurements.      Load these data into a matrix called 'timtemp.dat' using aneditor to build an ASCII file.            Time(sec)        Temp-T1(K)      Temp-T2(K)               0.0            306            125               1.0            305            121               2.0            312            123               3.0            309            122               4.0            308            124               5.0            299            129               6.0            311            122               7.0            303            122               8.0            306            123               9.0            303            127              10.0            306            124              11.0            304            123      Execute the commands at the beginning of the lesson above andobserve the results. Note that when the argument is 'timtemp', amatrix, the result is a 1x3 vector.  For example, the command           M = max(timtemp)gives          M = 11  312  129      If the argument is a single column from the matrix, thecommand identifies the particular column desired. The command           M2 = max(timtemp(:,2))gives          M2 = 312      If the variance of a set of data in a column of the matrix isdesired, the standard deviation is squared. The command           T1_var = (std(timtemp(:,2)))^2gives          T1_var = 13.2727 

Page 19: A Brief List of Matlab Commands

     If the standard deviation of the matrix of data is found using           STDDEV = std(timtemp)gives          STDDEV = 3.6056  3.6432  2.3012 Note that the command                               VAR = STDDEV^2 is not acceptable; however, the command                               VAR = STDDEV.^2 is acceptable, creating the results,                                                  VAR = 13.0000  13.2727  5.2955USING m-FILES - SCRATCH and FUNCTION FILES      Sometimes it is convenient to write a number of lines of'matlab' code before executing the commands.  We have seen how thiscan be accomplished using the line continuation ellipsis; however,it was noted in this approach that any mistake in the code requiredthe entire string to be entered again.  Using an m-file we canwrite a number of lines of 'matlab' code and store it in a filewhose name we select with the suffix  '.m' added.  Subsequently thecommand string or file content can be executed by invoking the nameof the file while in 'matlab'.  This application is called aSCRATCH FILE.      On occasion it is convenient to express a function in 'matlab'rather than calculating or defining a particular matrix.  The many'matlab' stored functions such as sin(x) and log(x) are examples offunctions.  We can write functions of our definition to evaluateparameters of our particular interest.  This application of m-filesis called FUNCTION FILES. SCRATCH FILES      A scratch file must be prepared in a text editor in ASCIIformat and stored in the directory from which you invoked thecommand to download 'matlab'.  The name can be any legitimate filename with the '.m' suffix.      As an example, suppose we wish to prepare a x-y plot of thefunction                          y = e-x/10 sin(x)    0 x ø 10 . To accomplish this using a scratch ".m-file", we will call the file'explot.m'.  Open the file in a text editor and type the codebelow.  (Note the use of the '%' in line 1 below to create acomment.  Any text or commands typed on a line after the'%' will betreated as a comment and ignored in the executable code.)% A scratch m-file to plot exp(-x/10)sin(x)x = [ 0:.2:10 ];y = exp(-x/10) .* sin(x);plot(x,y),...

Page 20: A Brief List of Matlab Commands

title('EXPONENTIAL DAMPED SINE FUNCTION'),...xlabel('x'),...ylabel('y'),...text(.6,.7,'y = exp(-x/10)*sin(x)','sc')      Store this file under the name 'explot.m in your 'matlab'directory.  Now when you are in 'matlab', any time you type thecommand 'explot' the x-y plot of the damped exponential sinefunction will appear. FUNCTION FILES      Suppose that you wish to have in your 'matlab' workspace afunction that calculates the sine of the angle when the argument isin degrees.  The matlab function sin(x) requires that x be inradians.  A function can be written that use the 'matlab' sin(x)function, where x is in radians, to accomplish the objective ofcalculating the sine of an argument expressed in degrees.  Again,as in the case of the scratch file, we must prepare the file inASCII format using a text editor, and we must add the suffix '.m'to the file.  HERE THE NAME OF THE FILE MUST BE THE NAME OF THEFUNCTION. The following code will accomplish our objective.  Note that thefirst line must always begin with the word "function" followed bythe name of the function expressed as " y = function-name".  Herethe function name is "sind(x)".  This is the name by which we willcall for the function once it is stored. function y = sind(x)% This function calculates the sine when the argument is degrees% Note that array multiplication and division allows this to% operate on scalars, vectors and matrices.y = sin( x .* pi ./ 180 )  Again, note the rule in writing the function is to express in thefirst line of the file the word 'function', followed by       y = function call,here 'sind' with the function argument in parentheses, 'x' is thefunction call.  Thus,      function y=sind(x) Now every time we type sind(x) in 'matlab', it will return thevalue of the sine function calculated under the assumption that xis in degrees.  Of course any matrix or expression involving amatrix can be written in the argument.ALGEBRAIC OPERATIONS IN MATLAB Scalar Calculations. The common arithmetic operators used inspreadsheets and programming languages such as BASIC are used in'matlab'. In addition a distinction is made between right and leftdivision. The arithmetic operators are      +         addition            -         subtraction

Page 21: A Brief List of Matlab Commands

     *         multiplication     /         right division (a/b means a ÷ b)     \         left division  (a\b means b ÷ a)     ^         exponentiation  When a single line of code includes more than one of theseoperators the precedence or order of the calculations follows thebelow order:           Precedence                Operation               1         parentheses               2         exponentiation, left to right               3         multiplication and division, left  right               4         addition and subtraction, left  right These rules are applied to scalar quantities (i.e., 1x1 matrices)in the ordinary manner. (Below we will discover that nonscalarmatrices require additional rules for the application of theseoperators!!) For example,      3*4      executed in 'matlab' gives     ans=12      4/5      executed in 'matlab' gives     ans=.8000      4\5      executed in 'matlab' gives     ans=1.2500      x = pi/2; y = sin(x)        executed in 'matlab' gives     y = 1      z = 0; w = exp(4*z)/5       executed in 'matlab" gives     z= .2000 Note that many programmers will prefer to write the expression forw above in the format                              w = (exp(4*x))/5which gives the same result and is sometimes less confusing whenthe string of arithmetic operations is long. Using 'matlab', carryout some simple arithmetic operations with scalars you define. Indoing so utilize the 'matlab' functions sqrt(x), abs(s), sin(x),asin(x), atan(x), atan2(x), log(x), and log10(x) as well as exp(x).Many other functions are available in 'matlab' and can be found inthe documentation.      Matrix Calculations. Because matrices are made up of a numberof elements and not a single number (except for the 1x1 scalarmatrix), the ordinary rules of commutative, associative anddistributive operations in arithmetic do not always follow.Moreover, a number of important but common-sense rules will prevailin matrix algebra and 'matlab' when dealing with nonscalarquantities. Addition and Subtraction of Matrices.  Only matrices of the SAMEORDER can be added or subtracted. When two matrices of the sameorder are added or subtracted in matrix algebra, the individual

Page 22: A Brief List of Matlab Commands

elements are added or subtracted. Thus the distributive ruleapplies.      A + B = B + A         and  A - B = B - A If C = A + B then each element Cij = Aij + Bij. Define A and B as follows:      A=[1 2 3; 3 3 3; 5 3 1]     B=[2 -3 4;2 -2 2; 0 4 0] Then note that           C = A + B    and   C = B + Agives               C =                    3  -1   7                    5   1   5                    5   7   1 Now define the row vector      x= [3  5  7] and the column vector      y = [4; -1; -3] Note that the operation      z = x + y is not valid!  It is not valid because the two matrices do not havethe same order. (x is a 1x3 matrix and y is a 3x1 matrix.)  Addingany number of 1x1 matrices or scalars is permissible and followsthe ordinary rules of arithmetic because the 1x1 matrix is ascalar. Adding two vectors is permissible so long as each is a rowvector (1xn matrix) or column vector (nx1 matrix). Of course anynumber of vectors can be added or subtracted, the result being thearithmetic sum of the individual elements in the column or rowvectors. Square matrices can always be added or subtracted so longas they are of the same order. A 4x4 square matrix can not be addedto a 3x3 square matrix, because they are not of the same order,although both matrices are square. Multiplication of Matrices. Matrix multiplication, though straight-forward in definition, is more complex than arithmeticmultiplication because each matrix contains a number of elements.Recall that with vector multiplication, the existence of a numberof elements in the vector resulted in two concepts ofmultiplication, the scalar product and the vector product. Matrixmultiplication has its array of special rules as well.      In matrix multiplication, the elements of the product, C, oftwo matrices A*B are calculated from 

Page 23: A Brief List of Matlab Commands

          Cij = ‘ Aik * Bkj To form this sum, the number of columns of the first or left matrix(A) must be equal to the number of rows in the second or rightmatrix (B). The resulting product, matrix C, has an order for whichthe number of rows equals the number of rows of the first (left)matrix (A) and the product (C) has a number of columns equal to thenumber of columns in the second (right) matrix (B).  It is clearthat A*B IS NOT NECESSARILY EQUAL TO B*A!  It is also clear thatA*B and B*A only exist for square matrices!       Consider the simple product of two square 2x2 matrices.      a = [ 1 2; 3 4];     b = [ 8 7; 6 5]; Calling the product c = a*b      c11 = a11*b11 + a12*b21     c12 = a11*b12 + a12*b22     c21 = a21*b11 + a22*b21     c22 = a21*b12 + a22*b22 Carry out the calculations by hand and verify the result using'matlab'.  Next, consider the following matrix product of a 3x2matrix X and a 2x4 matrix Y.      X = [2  3 ; 4 -1 ; 0  7];     Y = [5  -6  7  2 ; 1  2  3  6]; First, note that the matrix product X*Y exists because X has thesame number of columns (2) as Y has rows (2). (Note that Y*X doesNOT exist!)  If the product of X*Y is called C, the matrix C mustbe a 3x4 matrix.  Again, carry out the calculations by hand andverify the result using 'matlab'.      Note that the PRODUCT OF A SCALAR AND A MATRIX is a matrix inwhich every element of the matrix has been multiplied by thescalar.  Verify this by recalling the matrix X defined above, andcarry out the product 3*X on 'matlab'.  (Note that this can bewritten X*3 as well as 3*X, because quantity '3' is scalar.) ARRAY PRODUCTS      Recall that addition and subtraction of matrices involvedaddition or subtraction of the individual elements of the matrices.Sometimes it is desired to simply multiply or divide each elementof an matrix by the corresponding element of another matrix. Theseare called 'array operations" in 'matlab'.  Array or element-by-element operations are executed when the operator is preceded by a'.' (period).  Thus      a .* b    multiplies each element of a by the respective               element of b     a ./ b    divides each element of a by the respective element               of b     a .\ b    divides each element of b by the respective element

Page 24: A Brief List of Matlab Commands

               of a     a .^ b    raise each element of a by the respective b element     For example, if matrices G and H are defined      G = [ 1  3  5; 2  4  6];     H = [-4  0  3; 1  9  8];      G .* H = [ -4   0  15                 2  36  48 ] TRANSPOSE OF A MATRIX      The transpose of a matrix is obtained by interchanging therows and columns. The 'matlab' operator that creates the transposeis the single quotation mark, '. Recalling the matrix G      G' = [  1   2             3   4             5   6 ] Note that the transpose of a m x n matrix creates a n x m matrix.One of the most useful operations involving the transpose is thatof creating a column vector from a row vector, or a row vector froma column  vector. INNER (SCALAR) PRODUCT OF TWO VECTORS      The scalar or inner product of two row vectors, G1 and G2 isfound as follows. Create the row vectors for this example bydecomposing the matrix G defined above.      G1 = G(1,:)     G2 = G(2,:) Then the inner product of the 1x3 row vector G1 and the 1x3 rowvector G2 is      G1 * G2' = 44 Verify this result by carrying out the operations on 'matlab'.      If the two vectors are each column vectors, then the innerproduct must be formed by the matrix product of the transpose of acolumn vector times a column vector, thus creating an operation inwhich a  1 x n  matrix is multiplied with a  n x 1  matrix.      In summary, note that the inner product must always be theproduct of a row vector times a column vector. OUTER PRODUCT OF TWO VECTORS      If two row vectors exist, G1 and G2 as defined above, theouter product is simply      G1' * G2       {Note G1' is 3x1 and G2 is 1x3} and the result is a square matrix in contrast to the scalar result

Page 25: A Brief List of Matlab Commands

for the inner product.  DON'T CONFUSE THE OUTER PRODUCT WITH THEVECTOR PRODUCT IN MECHANICS!  If the two vectors are columnvectors, the outer product must be formed by the product of onevector times the transpose of the second!  OTHER OPERATIONS ON MATRICES      As noted above, many functions that exist can be applieddirectly to a matrix by simply allowing the function to operate oneach element of the matrix array. This is true for thetrigonometric functions and their inverse. It is true also for theexponential function, ex, exp(),  and the logarithmic functions,log() and log10().      Exponential operations (using ^) on matrices are quitedifferent from their use with scalars.  If W is a square matrixW^2 implies W*W which is quite different from W.*W.  Be certain ofyour intent before raising a matrix to an exponential power.  Ofcourse W^2 only exists if W is a square matrix.SPECIAL MATRICES      A number of special functions exist in 'matlab' to createspecial or unusual matrices.  For example, matrices with elementvalues of zero or 1 are sometimes useful.      zeros(4) creates a square matrix (4 x 4) whose elements are zero.      zeros(3,2) creates a 3 row, 2 column matrix of zeros.      Similarly the commands ones(4) creates a 4 x 4 square matrixwhose elements are 1's and 'ones(3,2)' creates a 3x2 matrix whoseelements are 1's.      If a m x n matrix, say A, already exists, the command'ones(A)' creates an m x n matrix of 1's.  The command 'zeros(A)'creates an mxn matrix of 0's.  Note that these commands do notalter the previously defined matrix A, which is only a basis forthe size of the matrix created by commands  zeros()  and  ones().      The identity matrix is a square matrix with 1's on thediagonal and 0's off the diagonal.  Thus a 4x4 identity matrix, a,is      a=[1 0 0 0        0 1 0 0        0 0 1 0        0 0 0 1] This matrix can be created with the 'eye' function. Thus,      a = eye(4) 

Page 26: A Brief List of Matlab Commands

The 'eye' function will create non-square matrices. Thus                eye(3,2)creates               1  0               0  1               0  0and                eye(2,3)creates                1 0 0               0 1 0  PRACTICE 1. The first four terms of the fourier series for the square wavewhose amplitude is 5 and whose period is 2ƒ is      y = (20/ƒ)[sinx  + (1/3)sin3x + (1/5)sin5x + (1/7)sin7x)] Calculate this series, term by term, and plot the results for eachpartial sum.

 

Matlab Commands List

The following list of commands can be very useful for future reference. Use "help" in Matlab for more information on how to use the commands.

In these tutorials, we use commands both from Matlab and from the Control Systems Toolbox, as well as some commands/functions which we wrote ourselves. For those commands/functions which are not standard in Matlab, we give links to their descriptions. For more information on writing Matlab functions, see thefunction page.

Note:Matlab commands from the control system toolbox are highlighted in red.Non-standard Matlab commands are highlighted in green.

Command Description

Page 27: A Brief List of Matlab Commands

abs Absolute value

acker Compute the K matrix to place the poles of A-BK, see also place

axis Set the scale of the current plot, see also plot, figure

bode Draw the Bode plot, see also logspace, margin, nyquist1

c2dm Continuous system to discrete system

clf Clear figure (use clg in Matlab 3.5)

conv Convolution (useful for multiplying polynomials), see also deconv

ctrb The controllability matrix, see also obsv

deconv Deconvolution and polynomial division, see also conv

det Find the determinant of a matrix

dimpulse Impulse response of discrete-time linear systems, see also dstep

dlqr Linear-quadratic requlator design for discrete-time systems, see also lqr

dlsim Simulation of discrete-time linear systems, see also lsim

dstep Step response of discrete-time linear systems, see also stairs

eig Compute the eigenvalues of a matrix

eps Matlab's numerical tolerance

feedback Feedback connection of two systems.

figure Create a new figure or redefine the current figure, see also subplot, axis

for For, next loop

format Number format (significant digits, exponents)

function Creates function m-files

grid Draw the grid lines on the current plot

gtext Add a piece of text to the current plot, see also text

help HELP!

Page 28: A Brief List of Matlab Commands

hold Hold the current graph, see also figure

if Conditionally execute statements

imag Returns the imaginary part of a complex number, see also real

impulse Impulse response of continuous-time linear systems, see also step, lsim, dlsim

input Prompt for user input

inv Find the inverse of a matrix

jgridGenerate grid lines of constant damping ratio (zeta) and settling time (sigma), see also sgrid, sigrid, zgrid

legend Graph legend

length Length of a vector, see also size

linspace Returns a linearly spaced vector

lnyquist1 Produce a Nyquist plot on a logarithmic scale, see also nyquist1

log natural logarithm, also log10: common logarithm

loglog Plot using log-log scale, also semilogx/semilogy

logspace Returns a logarithmically spaced vector

lqr Linear quadratic regulator design for continuous systems, see also dlqr

lsim Simulate a linear system, see also step, impulse, dlsim.

margin Returns the gain margin, phase margin, and crossover frequencies, see also bode

norm Norm of a vector

nyquist1Draw the Nyquist plot, see also lnyquist1. Note this command was written to replace the Matlab standard command nyquist to get more accurate Nyquist plots.

obsv The observability matrix, see also ctrb

ones Returns a vector or matrix of ones, see also zeros

place Compute the K matrix to place the poles of A-BK, see also acker

plot Draw a plot, see also figure, axis, subplot.

Page 29: A Brief List of Matlab Commands

poly Returns the characteristic polynomial

polyadd Add two different polynomials

polyval Polynomial evaluation

print Print the current plot (to a printer or postscript file)

pzmap Pole-zero map of linear systems

rank Find the number of linearly independent rows or columns of a matrix

real Returns the real part of a complex number, see also imag

rlocfind Find the value of k and the poles at the selected point

rlocus Draw the root locus

roots Find the roots of a polynomial

rscale Find the scale factor for a full-state feedback system

setSet(gca,'Xtick',xticks,'Ytick',yticks) to control the number and spacing of tick marks on the axes

series Series interconnection of Linear time-independent systems

sgridGenerate grid lines of constant damping ratio (zeta) and natural frequency (Wn), see also jgrid, sigrid, zgrid

sigrid Generate grid lines of constant settling time (sigma), see also jgrid, sgrid, zgrid

size Gives the dimension of a vector or matrix, see also length

sqrt Square root

ss Create state-space models or convert LTI model to state space, see also tf

ss2tf State-space to transfer function representation, see also tf2ss

ss2zp State-space to pole-zero representation, see also zp2ss

stairs Stairstep plot for discreste response, see also dstep

step Plot the step response, see also impulse, lsim, dlsim.

subplot Divide the plot window up into pieces, see also plot, figure

Page 30: A Brief List of Matlab Commands

text Add a piece of text to the current plot, see also title, xlabel, ylabel, gtext

tf Creation of transfer functions or conversion to transfer function, see also ss

tf2ss Transfer function to state-space representation, see also ss2tf

tf2zp Transfer function to Pole-zero representation, see also zp2tf

title Add a title to the current plot

wbw Returns the bandwidth frequency given the damping ratio and the rise or settling time.

xlabel/ylabel Add a label to the horizontal/vertical axis of the current plot, see also title, text, gtext

zeros Returns a vector or matrix of zeros

zgridGenerates grid lines of constant damping ratio (zeta) and natural frequency (Wn), see also sgrid, jgrid, sigrid

zp2ss Pole-zero to state-space representation, see also ss2zp

zp2tf Pole-zero to transfer function representation, see also tf2zp

Basic Matlab CommandsDerrick HasterokJanuary 27, 20051 IntroductionMatlab has a multitude of syntax and basic commands. Begining to programin a new language can be a daunting task. This document is meant as a helpto make getting started with Matlab a bit easier. Listed below is a few of thebasic commands and a few of their properties. This list is not exhaustive, noris it meant to be. The Matlab command ’help’ is your friend!

2 System Commandscd - Change directory.clc - Clears command window.clear - Clears variables from workspace.close - Closes figures.delete - Deletes file.ls - Lists directry.help - Tells you how to use a command.mkdir - Makes directory.pwd - Prints working directory.who - Lists current variables on workspace.whos - Lists current variables and size.why - Just try it if you get annoyed.

3 Operators3.1 Arithmetic operators

Page 31: A Brief List of Matlab Commands

+ - Plus- - Minus* - Matrix multiply.* - Array multiply^ - Matrix power.^ - Array power/ - Right matrix divide1./ - Right array divide3.2 Boolean operators== - Equal~= - Not equal< - Less than> - Greater than<= - Less than or equal>= - Greater than or equal3.3 Logical operators& - Logical AND| - Logical OR~ - Logical NOT3.4 Special commands: - Span operator [1:5] = [1 2 3 4 5]( ) - Operation grouping[ ] - Vector and matrix delimiter. - Decimal point.. - Parent directory... - Continuation of command to next line, - Separator; - End line or row% - Comment= - Assignment operator’ - String delimiter.’ - Transpose’ - Complex conjugate transpose

4 Basic Syntaxif - Conditionally execute statements.else - IF statement condition.elseif - IF statement condition.end - Terminate scope of FOR, WHILE, SWITCH, TRY and IF statements.for - Repeat statements a specific number of times.while - Repeat statements an indefinite number of times.break - Terminate execution of WHILE or FOR loop.continue - Pass control to the next iteration of FOR or WHILE loop.function - Add new function.return - Return to invoking function.2error - Display error message and abort function.disp - Display an array.feval - Execute function specified by string.

5 Elementary Math Functions5.1 Trigonometricsin - Sine.asin - Inverse sine.

Page 32: A Brief List of Matlab Commands

cos - Cosine.acos - Inverse cosine.tan - Tangent.atan - Inverse tangent.atan2 - Four quadrant inverse tangent.5.2 Basicsqrt - Square root.exp - Exponential.log - Natural logarithm.log10 - Common (base 10) logarithm.factorial - Factorial function.5.3 Complexabs - Absolute value.conj - Complex conjugate.real - Complex real part.imag - Complex imaginary part.isreal - True for real array.5.4 Roundingfloor - Round towards minus infinity.ceil - Round towards plus infinity.round - Round towards nearest integer.mod - Modulus.5.5 Matrix and Othernorm - Matrix or vector norm.det - Determinant.inv - Matrix inverse.eig - Eigenvalues and eigenvectors.cross - Vector cross product.3dot - Vector dot product.

6 File input/outputinput - Prompt for user input.load - Load workspace from MATLAB (MAT) file.save - Save data to MATLAB (MAT) file.

7 Plot commands7.1 2D Graphsplot - Linear plot.loglog - Log-log scale plot.semilogx - Semi-log scale plot.semilogy - Semi-log scale plot.axis - Control axis scaling and appearance.hold - Hold current graph.title - Graph title.xlabel - X-axis label.ylabel - Y-axis label.get - Gets plot properties.set - Sets plot properties.7.2 Matlab PLOT stylesColor Line Type Marker Typey - yellow - - solid . - pointm - magenta : - dotted o - circlec - cyan -. - dashdot x - x-markr - red -- - dashed + - plus

Page 33: A Brief List of Matlab Commands

g - green * - starb - blue s - squarew - white d - diamondk - black v - triangle (down)^ - triangle (up)< - triangle (left)> - triangle (rightp - pentagramh - hexagram4

General Reference of MATLAB CommandsThere are many MATLAB features which cannot be included in these introductory notes. Listed below are some of the MATLAB functions and operators available, grouped by subject area. Use the online help facility, or consult the MATLAB User's Guide, for more detailed information on the functions.

There are many functions beyond these. There exist, in particular, several "toolboxes" of functions for specific areas, including those for signal processing, control theory, dynamical systems (system identification), and chemometrics. These can be explored via the command

help

General Functions

help help facility demo run demonstrations who list variables in memory what list M-files on disk size row and column dimensions length vector length clear clear workspace computer type of computer ^C local abort exit exit MATLAB quit same as exit

Matrix and Array Operators

Matrix Operators Array Operators

+ addition + addition - subtraction - subtraction * multiplication .* multiplication / right division ./ right division \ left division .\ Left division ^ power .^ power ' conjugate transpose .' transpose

Page 34: A Brief List of Matlab Commands

Relational and Logical Operators

less than & and <= less than or equal | or > greater than ~ not >= greater than or equal == equal ~= not equal

Special Characters

= assignment statement [ used to form vectors and matrices ] see [ ( arithmetic expression precedence ) see ( . decimal point ... continue statement to next line , separate subscripts and function arguments ; end rows, suppress printing comments : subscripting, vector generation ! execute operating system command

Special Values

ans answer when expression not assigned eps floating point precision pi 3.14159...... i,j square root of -1 inf oo NaN Not-a-Number clock wall clock date date flops floating point operation count nargin number of function input arguments nargout number of function output arguments

Disk- and File-related Commands

chdir change current directory delete delete file diary diary of the session dir directory of files on disk load load variables from file save save variables to file type list function or file what show M-files on disk fprintf write to a file pack compact memory via save

Page 35: A Brief List of Matlab Commands

Special Matrices

compan companion diag diagonal eye identity gallery esoteric hadamard Hadamard hankel Hankel hilb Hilbert invhilb inverse Hilbert linspace linearly spaced vectors logspace logarithmically spaced vectors magic magic square meshdom domain for mesh points ones constant rand random elements toeplitz Toeplitz vander Vandermonde zeros zero

Matrix Manipulation

rot90 rotation fliplr flip matrix left-to-right flipud flip matrix up-to-down diag diagonal matrices tril lower triangular part triu upper triangular part reshape reshape .' transpose : convert matrix to single column; A (: )

Relational and Logical Functions

any logical conditions all logical conditions find find array indices of logical values isnan detect NaNs finite detect infinities isempty detect empty matrices isstr detect string variables strcomp compare string variables

Control Flow

elseif used with if else used with if end terminate if, for, while for repeat statements a number of times while do while break break out of for and while loops

Page 36: A Brief List of Matlab Commands

return return from functions pause pause until key pressed

Programming and M-Files

input get numbers from keyboard keyboard call keyboard as M-file error display error message function define function eval interpret text in variables feval evaluate function given by string echo enable command echoing exist check if variables exist casesen set case sensitivity global define global variables startup startup M-file getenv get environment string menu select item from menu etime elapsed time

Text and Strings

abs convert string to ASCII values eval evaluate text macro num2str convert number to string int2str convert integer to string setstr set flag indicating matrix is a string sprintf convert number to string isstr detect string variables strcomp compare string variables hex2num convert hex string to number

Command Window

home move cursor home format set output display format disp display matrix or text fprintf print formatted number echo enable command echoing

Graph Features

plot linear X-Y plot loglog loglog X-Y plot semilogx semi-log X-Y plot semilogy semi-log X-Y plot polar polar plot mesh 3-dimensional mesh surface contour contour plot meshdom domain for mesh plots bar bar charts

Page 37: A Brief List of Matlab Commands

stairs stairstep graph errorbar add error bars

Graph Annotation

title plot title xlabel x-axis label ylabel y-axis label grid draw grid lines text arbitrarily position text gtext mouse-positioned text ginput graphics input

Graph Window Control

axis manual axis scaling hold hold plot on screen shg show graph window clg clear graph window subplot split graph window

Graph Window Hardcopy Commands

print send graph to printer prtsc screen dump meta graphics metafile

Elementary Math Functions

abs absolute value or complex magnitude angle phase angle sqrt square root real real part imag imaginary part conj complex conjugate round round to nearest integer fix round toward zero floor round towards -oo ceil round toward oo sign signum function rem remainder exp exponential base e log natural logarithm logl0 log base 10

Trigonometric Functions

sin sine cos cosine

Page 38: A Brief List of Matlab Commands

tan tangent asin arcsine acos arccosine atan arctangent atan2 four quadrant arctangent sinh hyperbolic sine cosh hyperbolic cosine tanh hyperbolic tangent asinh hyperbolic arcsine acosh hyperbolic arccosine atanh hyperbolic arctangent

Special Functions

bessel bessel function gamma gamma function rat rational approximation erf error function inverf inverse error function ellipk complete elliptic integral of first kind ellipj Jacobian elliptic integral

Decompositions and Factorizations

balance balanced form backsub backsubstitution cdf2rdf convert complex-diagonal to real-diagonal chol Cholesky factorization eig eigenvalues and eigenvectors hess Hessenberg form inv inverse lu factors from Gaussian elimination nnls nonnegative least squares null null space orth orthogonalization pinv pseudoinverse qr orthogonal-triangular decomposition qz QZ algorithm rref reduced row echelon form schur Schur decomposition svd singular value decomposition

Matrix Conditioning

cond condition number in 2-norm norm 1-norm,2-norm,F-norm,oo-norm rank rank rcond condition estimate (reciprocal)

Elementary Matrix Functions

Page 39: A Brief List of Matlab Commands

expm matrix exponential logm matrix logarithm sqrtm matrix square root funm arbitrary matrix function poly characteristic polynomial det determinant trace trace kron Kronecker tensor product

Polynomials

poly characteristic polynomial roots polynomial roots-companion matrix method rootsl polynomial roots-Laguerre's method polyval polynomial evaluation polyvalm matrix polynomial evaluation conv multiplication deconv division residue partial-fraction expansion polyfit polynomial curve fitting

Column-Wise Data Analysis

max maximum value min minimum value mean mean value median median value std standard deviation sort sorting sum sum of elements prod product of elements cumsum cumulative sum of elements cumprod cumulative product of elements diff approximate derivatives hist histograms corrcoef correlation coefficients cov covariance matrix cplxpair reorder into complex pairs

Signal Processing

abs complex magnitude angle phase angle conv convolution corrcoef correlation coefficients cov covariance deconv deconvolution fft radix-2 fast Fourier transform fft2 two-dimensional FFT ifft inverse fast Fourier transform ifft2 inverse 2-D FFT fftshift FFT rearrangement

Page 40: A Brief List of Matlab Commands

Interpolation

spline cubic spline table1 1-D table look-up table2 2-D table look-up

Differential Equation Solution

ode23 2nd/3rd order Runge-Kutta method ode45 4th/5th order Runge-Kutta-Fehlberg method

Nonlinear Equations and Optimization

fmin minimum of a function of one variable fmins minimum of a multivariable function fsolve solution of a system of nonlinear equations (zeros of a multivariable function) fzero zero of a function of one variable

Other Matlab Hints

Click on an item listed below to access additional MATLAB-related hints.

A General Introduction to MATLAB Algorithm Efficiency Comparisons The Basics of MATLAB MATLAB Command Summary FOR, WHILE, and IF Loops Formatting Your MATLAB Output Generating MATLAB Graphics Matrix-Building Functions Entering Matrices in MATLAB Matrix Operating Functions Matrix Operations A Brief Explanation of M-Files Managing M-Files Printing a Hardcopy of Your MATLAB Session MATLAB Scalar Functions MATLAB Statements, Expressions and Variables Submatrices and Colon Notation Vector Functions

Return to ACS home page.

Page 41: A Brief List of Matlab Commands

Please send comments and suggestions to

[email protected]

MATLAB Commands ListThe following list of commands can be very useful for future reference. Use "help" inMATLAB for more information on how to use the commands.In these tutorials, we use commands both from MATLAB and from the Control SystemsToolbox, as well as some commands/functions which we wrote ourselves. For thosecommands/functions which are not standard in MATLAB, we give links to theirdescriptions.Note: MATLAB commands from the control system toolbox are highlighted in red.Non-standard MATLAB commands are highlighted in green.Command Descriptionabs Absolute valueacker Compute the K matrix to place the poles of A-BK, see also placeaxis Set the scale of the current plot, see also plot, figurebode Draw the Bode plot, see also logspace, margin, nyquist1c2d Continuous system to discrete systemclf Clear figureconv Convolution (useful for multiplying polynomials), see also deconvctrb The controllability matrix, see also obsvdeconv Deconvolution and polynomial division, see also convdet Find the determinant of a matrixdlqr Linear-quadratic regulator design for discrete-time systems, see also lqreig Compute the eigenvalues of a matrixeps MATLAB's numerical tolerancefeedback Connect linear systems in a feedback loopfigure Create a new figure or redefine the current figure, see also subplot, axisfor For, next loopformat Number format (significant digits, exponents)function Creates function m-filesgrid Draw the grid lines on the current plotgtext Add a piece of text to the current plot, see also texthelp HELP!hold Hold the current graph, see also figureif Conditionally execute statementsimag Returns the imaginary part of a complex number, see also realimpulse Impulse response of linear systems, see also step, lsiminput Prompt for user inputinv Find the inverse of a matrixlegend Graph legendlength Length of a vector, see also sizelinspace Returns a linearly spaced vector

Page 42: A Brief List of Matlab Commands

lnyquist Produce a Nyquist plot on a logarithmic scale, see also nyquist1log natural logarithm, also log10: common logarithmloglog Plot using log-log scale, also semilogx/semilogylogspace Returns a logarithmically spaced vectorlqr Linear quadratic regulator design for continuous systems, see also dlqrlsim Simulate a linear system, see also step, impulsemargin Returns the gain margin, phase margin, and crossover frequencies, see alsobodeminreal Produces a minimal realization of a system (forces pole/zero cancellations)norm Norm of a vectornyquist1Draw the Nyquist plot, see also lnyquist. Note this command was written toreplace the MATLAB standard command nyquist to get more accurateNyquist plots.obsv The observability matrix, see also ctrbones Returns a vector or matrix of ones, see also zerosplace Compute the K matrix to place the poles of A-BK, see also ackerplot Draw a plot, see also figure, axis, subplot.poly Returns the characteristic polynomialpolyval Polynomial evaluationprint Print the current plot (to a printer or postscript file)pzmap Pole-zero map of linear systemsrank Find the number of linearly independent rows or columns of a matrixreal Returns the real part of a complex number, see also imagrlocfind Find the value of k and the poles at the selected pointrlocus Draw the root locusroots Find the roots of a polynomialrscale Find the scale factor for a full-state feedback systemset Set(gca,'Xtick',xticks,'Ytick',yticks) to control the number and spacing oftick marks on the axessgrid Generate grid lines of constant damping ratio (zeta) and natural frequency(Wn), see also sigrid, zgridsigrid Generate grid lines of constant settling time (sigma), see also sgrid, zgridsize Gives the dimension of a vector or matrix, see also lengthsqrt Square rootss Create state-space models or convert LTI model to state space, see also tfssdata Access to state-space data. See also tfdatastairs Stairstep plot for discrete responsestep Plot the step response, see also impulse, lsimsubplot Divide the plot window up into pieces, see also plot, figuretext Add a piece of text to the current plot, see also title, xlabel, ylabel, gtexttf Creation of transfer functions or conversion to transfer function, see also sstfdata Access to transfer function data, see also ssdatatitle Add a title to the current plotwbw Returns the bandwidth frequency given the damping ratio and the rise orsettling time.

Page 43: A Brief List of Matlab Commands

xlabel/ylabel Add a label to the horizontal/vertical axis of the current plot, see also title,text, gtextzeros Returns a vector or matrix of zeroszgrid Generates grid lines of constant damping ratio (zeta) and natural frequency(Wn), see also sgrid, sigrid