Introduction to Matlab

ENME462


This tutorial is meant to be read while logged into a UNIX machine or a PC in the instructional labs.

Unix:

Make a new directory called "matlab" or "me462" or whatever you like (use the "mkdir" command, and then "cd" into that directory). Open up your favorite editor and an xterm; type "tap matlab" in the xterm window, then the command "matlab". Another window should open with a plot in it. This might take a while depending on how many other things are running. Be patient.

PC:

Open up an editor and also run matlab by double clicking on its icon in the Engineering Software subgroup. You can use your favorite editor as long as it produces flat ascii files. The built-in matlab editor or Notepad will work fine. Alternate method: you will for now have to use X-win, a program found under the Internet program group. Once X-win is run, it will connect to a Unix machine and you will be able to log on and proceed as in the Unix side.
Although you can type commands directly into matlab, it is perhaps easiest to put all of the commands that you will need together in an m-file, and just run the file. If you put all of your m-files in the same directory that you run matlab from, then matlab will always find them.

In this laboratory, we will practice some fundamentals in MATLAB. The following MATLAB commands will be used. You can use "help topic" to get information for the usage of a specific command.

   diag            - Generate diagonal matrix.
   poly            - Polynomial.
   polyval         - Evaluate polynomial.
   roots           - Find polynomial roots.
   exp             - Exponential.
   det             - Determinant.
   inv             - Matrix inverse.
   rank            - Matrix rank.
   eig             - Eigenvalues and eigenvectors.
   expm            - Matrix exponential.
   plot            - Linear plot.
   title           - Graph title.
   xlabel          - X-axis label.
   ylabel          - Y-axis label.
   print           - Print graph or save graph to file
You may also need to use the following operators and/or symbols:
Char    Name                         HELP topic

   +      Plus                         arith
   -      Minus                        arith
   *      Matrix multiplication        arith
   .*     Array multiplication         arith
   ^      Matrix power                 arith
   .^     Array power                  arith

   \      Backslash or left division   slash
   /      Slash or right division      slash
   ./     Array division               slash

   :      Colon                        colon

   ( )    Parentheses                  paren

   .      Decimal point                punct
   ;      Semicolon                    punct
   %      Comment                      punct
   '      Transpose and quote          punct
   =      Assignment                   punct
or you can try
   help matlab/ops
to get more infomation. To exit from MATLAB, type quit or exit at the MATLAB prompt, followed by the ``return''key.


1.1 Fundamental Expressions

Working in the MATLAB environment is straightforward since most commands are entered as you would write them mathematically. For example, entering
a=4/3
yields the MATLAB response
a=
1.3333
and assigns to variable a the value of 4 divided by 3.

If you do not care to create a new variable but want to know the value of an expression, you can type the expression by itself, e.g.,
4/3
which yields
ans=
1.3333
where ans is a dummy variable that stands for "answer."

If you prefer to create a new variable but do not wish to see the MATLAB response, type a semicolon at the end of the expression. For example,
b=4+7;
will create a new variable b whose value is 11, but MATLAB will not display the value of b. However, you can check the value of a variable at any time by entering the variable name at the prompt:
b
which yields
b=
11
Since a and b have been defined we can do the following:
c=a*(b-1)
which yields
c=
13.3333
If you are typing in an expression that does not fit on one line, use an ellipsis (three or more periods) at the end of the line and continue typing on the next line, e.g.,
p=1+2+...
3+4+6;
Arithmetic operators are the same as those commonly used except that * represents multiplication \ performs left devision, and ^ is the power operator. For the order in which MATLAB performs operations, the power operator ^ has precedence over multiplication * and division / and \, which have precedence over addition + and subtraction -. Precedence of like operators proceeds from left to right, but parentheses can be used affect the order of operation. Try
1+2^3/4*2
1+2^3/(4*2)
(1+2)^3/(4*2)
You should get the results of 5, 2, and 3.3750.

MATLAB has several predefined variables such as

i and j stand for square root of -1 which can be used to represent the complex numbers;
pi stands for pai;
Inf stands for infinity;
NaN stands for not a number (e.g. 0/0).
Try
c=4/0
d=Inf/Inf
y=sqrt(1+4*i)
z=exp(-1+3*j)
You should get the results of Inf, NaN, 1.6005+1.2496i, and -0.3642 + 0.0519i.

You have used functions sqrt and exp which stand for "square root" and " exponential. There are other MATLAB functions that are very useful. You can use help followed by a command name to get the information about the usage of the command.

So far, you have learned how to define your variables. If you want to save them for your future use, you can use save command and latter on use load command to re-load them. Use help to get information about how to use these commands.

You can create a script file (an m-file) called "lab1.m" in your editor and include all the commands you want in that file. Later on you can run the m-file by typing the name of the m-file under the MATLAB prompt, e.g.,
 
>> lab1

1.2 Matrices, Vectors, and Polynomials

Vectors are entered into MATLAB by enclosing the vector elements within a pair of brackets. Vectors may either be _row_ or _column_ vectors. For example, a row vector V1 can be defined as,
>>V1 = [1 2 3]

V1=
    1  2  3
And a column vector V2 can be defined as,
>>V2 = [1; 2; 3]

V2=
    1
    2
    3
As you can see, row elements are separated by spaces (or commas), and column elements are separated by semicolons. A column vector may be transformed into a row vector, and visa-versa, through the transpose operation, defined in MATLAB by placing a single quote (') after the vector definition. For example, the transpose of our column vector V2 is,
>>V2'

ans=

    1  2  3
A Matrix is a series of vectors of like-dimension appended together into a two-dimensional array. Matrices are entered into MATLAB by listing the elements of the matrix and enclosing them within a pair of brackets. Elements of a single row are separated by commas or blanks, and rows are separated by semicolons or carriage returns. For example,
>> A=[1 2; 3 4]
yields the MATLAB response
A=
1 2
3 4
>> A=[1,2
3,4]
would produce the same result.

To find the dimensions of a matrix use the size command, e.g.,
>> size(A)
ans=
2 2

SUBMATRICES

Individual matrix elements can be referenced using indices enclosed within parentheses. For example, to change the second element in the second row of matrix A to 5, type
>> A(2,2)=5
A =
1 2
3 5
If you add an element to a matrix beyond the existing size of the matrix then MATLAB automatically inserts zeros as needed to maintain a rectangular matrix:
>> A(3,3)=6
A =
1 2 0
3 5 0
0 0 6
Since a vector is simply a 1 x n or an n x 1 matrix, where n is any positive integer, you can generate vectors in the same way as matrices:
>> v= [sin(pi/3)  -7^3  a+1]
v=
0.8660 -343.0000 2.3333
Alternatively, special vectors can be created using the : operator. The command k=1:10 generates a row vector with elements from 1 to 10 with increment 1. Any other increment can be applied with a second : as follows:
>> knew = 1:0.25:2
knew =
1.0000 1.2500 1.5000 1.7500 2.0000
To add a row onto matrix A we type
>> A = [A;[7 8 9]]
A =
1 2 0
3 5 0
0 0 6
7 8 9
To extract the submatrix of A that consists of the first through third columns of the second through fouth rows use vectors as indices as follows:
>> B=A(2:4,1:3)
B =
3 5 0
0 0 6
7 8 9

SPECIAL MATRICES

>> D=diag([1 2 3])

D =
     1     0    0
     0     2    0
     0     0    3
You can create a dummy matrix with all zero elements using the zeros command. This is very useful when you need to create a null matrix which you will fill in element-for-element later.
Z = zeros(2,3)

Z = 
     0    0    0
     0    0    0

POLYNOMIALS AS MATRICES

Polynomials are described in MATLAB by row vectors with elements that are equal to the polynomial coefficients in order of decreasing powers. For example, to enter the polynomial p=s^2+5s +6 type
p=[1 5 6]
p =
1 5 6
Zero coefficients must be included to avoid confusion, i.e., q=s^3+5s+6 is entered as
q=[1 0 5 6]
q =
1 0 5 6
A polynomial can be evaluated using the polyval command. For example,
>> polyval(p,1)
ans =
12
gives the value of the polynomial p at s=1. Using the roots command is a convenient way to find the roots of a polynomial, e.g.,
>> r= roots(p)
r =
-3
-2

1.3 Matrix Operations and Functions

MATLAB performs matrix arithmetic as easily as it does scalar arithmetic. To add two matrices simply type
>> B+D
ans =
4 5 0
0 2 6
7 8 12
Similarly, to multiply two matrices do as you would for scalars,
>> B*D
ans =
3 10 0
0 0 18
7 16 27
Dividing by matrices is also straightforward once you understand how MATLAB interprets the divide symbols (/ and \). Suppose you want to solve for x in the equation P x = Q. To express the solution x=P^{-1}Q in MATLAB use left division as x=P\Q. Now suppose you want to solve y P = Q for y. The solution to this problem is y=Q P^{-1} which you can write in MATLAB using right division as y=Q/P.

Be careful with the inner dimensions of the two matrices being multiplied or divided which should be the same. Otherwise, MATLAB will tell you there are some bugs.

The power operator ^ also operates on the matrix as whole as long as the matrix is square. Other functions that perform operations on matrices include det(B), inv(B), rank(B), eig(B), and expm(B) which produce the determinant, inverse, rank, eigenvalues, and e^X respectively. Many of them require that the matrices be square.

At times you may want to consider a matrix as simply an array of numbers and operate on the array element by element. Specifically, you will create arrays to represent tables of data that you want to manipulate. MATLAB provides different ways of using functions to operate on arrays instead of matrices. For example, suppose you have a table of data that you have entered as an array called Data. Now suppose you would like to perform a root-mean-square calculation and need to find the square of each element in Data. Using a . you can convert arithmetic matrix operation into element-by-element operations (addition and subtraction are the same in either case). Specifically, preceding the operator with the . indicates array operations. To square each element in the array type Data.^2. Similarly, to multiply two arrays R and S (of the same dimensions) element by element type R.*S as follows:
>> R=[4 5 
0 1];
>> S=[2 3
4 6];
>> R.*S
ans =
8 15
0 6

1.4 Plotting

Let's see how to plot a vector using the "plot" command. First try
t=0:0.2:10;
y=sin(t);
plot(t,y)

This is a very basic plot; the first variable is on the horizontal axis and the second variable is on the vertical axis. You can change the style of the line by using a third option to "plot", try
plot(t,y,':')
Note that the colon is enclosed in single quotes and separated from the other arguments by a comma. You should get a dotted line. You can make it green (if you have a color monitor) by using
plot(t,y,'g:')
Other options that you might want to try are:
solid   -      red       r
dashed  --     green     g
dotted  :      blue      b
dashdot -.     white     w                  
or try
help plot
for more information.
Now let's put some useful labels on the plot so someone who looks at it knows what it is. Enter:
xlabel('Time in seconds');
ylabel('Sin(t)');
title('Sine Wave -- J. Doe, ENME362, LAB1');

To print, you need to know the name of the printer you want to use. This should be posted somewhere near the printer. Just type (within matlab)

print -P<printername>
If you would rather save the plot to print it later (say, you are logged in remotely and don't have a printer handy), then you would type
print -dps plot.ps
to save the plot in a postscript format in a file called "plot.ps" (in your current working directory.) Sometime later, you could print it using the command "qpr -q <printername> -ps plot.ps" from a GLUE machine, or if you are using a non-GLUE unix workstation to print, you should instead use the command "lpr -P<printername> plot.ps" since lpr is the standard Unix print service.

Using M-files in Matlab

For simple programs, entering your requests (commands) at the Matlab prompt is fast and efficient. However, as the number of commands increases, typing at the Matlab prompt becomes tedious. Matlab provides a logical solution to this problem. It allows you to place Matlab commands in a simple text file and then tell Matlab to open the file and evaluate commands exactly as it would if you had typed them at the Matlab prompt. These files are called batch files or script files or m-files. Batch files because the commands are executed sequentially as a batch, script files because Matlab simply follows the script found in the file and m-files because file names must end with the extension 'm' (You sure know that).

To create a batch m-file, you bring up a text editor window where you enter the Matlab commands. There are slightly different things you need to know for each platform.

Macintosh

Windows

Unix

You can either type commands directly into matlab, or put all of the commands that you will need together in an m-file, and just run the file. If you put all of your m-files in the same directory that you run matlab from, then matlab will always find them.

Important: When working in Windows environment you have to be careful when saving the m-file. You need to save the m-file in a directory which is in the path (Try the command [path] at the Matlab command prompt)of Matlab, otherwise when you try to run the m-file Matlab won't be able to find it!

Diary() -- Logging your Matlab Session

Matlab offers a very convenient way to save the text output you have during a session to a text file. This text file can later be printed as a record of your output. This is the recommended way to print out your output for Matlab-based assignments in this course!
The command to log your session is called diary. By typing
diary('diaryfilename')
a file called 'diaryfilename' will be created and all output to your Matlab command window will be written to this file until you type
diary off
To turn the diary back on again while writing to the same file, simply type
diary
('diary' by itself simply toggles the diary state).

Nise Tutorial Examples

Follow through the Nise example problems ch2p1 - ch2p9 (see Appendix B, pg. 852). These examples provide insight into various ways that polynomial expressions can be formed and manipulated in MatLab.


Assignment

Create a MATLAB m-file which will solve each of the following problems. For each problem, you need to turn in the following:
       (1) Printout of the m-file.
       (2) Printout of the MATLAB results when the m-file is run.
           Use the diary command to save the output to a file,
           then print this file to turn in.
       (3) Printouts of any plots requested.

1. Consider the following matrices and vectors:
              [-5   1   0]         [ 0 ]
          A = [ 0  -2   1]     b = [ 0 ]   c = [-1  1  0]
              [ 0   0   1]         [ 1 ]

(a) Suppose A x = b, find x.
(b) Suppose y A = c, find y.
(c) Let G(s) = c * inv(sI-A) * b, find G(0) and G(1).
(d) Define C_m = [b Ab A^2b], find the rank of C_m.
NOTE: the rank of a matrix is equal to the number of linearly independent rows or columns in the matrix. We'll be talking about this towards the end of the course, but for now you need to know that the rank of a matrix A is found in MATLAB using the rank() command. Type 'help rank' for more information. (e) Now consider an arbitrary nxn matrix A and nx1 vector b. Let C_m=[b Ab A^2b ... A^{n-1}b]. Write a script file (m-file) that comuptes the rank of C_m. Test this program out with several matrices and vector combinations with varying dimension. Note: you will need to do some programming to complete this problem. The program will need to (1) determine the size of A (=n) which is also equal to the size of C_m, (2) form C_m (regardless of n), and (3) find the rank of C_m. To do this you will probably want to use a for...next or while loop. To learn more about the syntax for these functions, type 'help for' or 'help while'.
2. Consider the function
                n(s)             n(s)=s^3 + 6.4 s^2 + 11.29 s + 6.76
        H(s) = ------   where    
                d(s)             d(s)=s^4 + 14 s^3 + 46s^2 +64s + 40
(a) Find n(-12), n(-10), d(-12), d(-10).
(b) Find H(-12), H(-10).
(c) Find all the values of s for which H(s) = 0. (d) Find all the values of s for which H(s) = inf. (d) Plot H(s) for s=0 through s=20. Label your axes appropriately.