LPPD, University of Illinois at Chicago
Director: Prof. Andreas A. Linninger
Objective
Research
People
Publications
Teaching
Reports
Employment
Contact Us
Home

 

Introduction to MATLAB

Developed by Libin Zhang under the guidance of Prof. A. Linninger

 Laboratory for Product and Process Design,
Department of Chemical Engineering, UIC

09/07/2002

09/05/2003 (Revised)

09/09/2005 (Revision 2)

 1. Working with the Command Window

On your Desktop (possibly behind this window), you should find a  labeled MatLab.  This is the first window you see when you launch MATLAB on a PC. 

In this way you can use MATLAB as a calculator. The basic operations and functions are represented by * for "times", / for "divided by", ^ for powers (i.e., 3^3 means "3 cubed"), abs for absolute value, sqrt for square root, exp for the exponential function to the base e, so exp(1)=2.718281828..., log for the logarithm function to the base e, sin, cos, and tan for the basic trig functions, cosh, sinh, tanh for the basic hyperbolic functions, and asin, acos, atan for the inverse trig functions.

6/3 

ans =

     2  

log10(100) 

ans =

     2   

Try typing sin(pi) and hit RETURN.  MATLAB should type in response something like:

ans =

     1.2246e-016

MATLAB has recognized sin as referring to the sine function, and pi as referring to p.  Of course sin(p)=0, but because of round-off error, MATLAB has given the numerical answer 1.224´10-16 (in scientific notation).  That's because MATLAB does arithmetic with double-precision numbers, which are only accurate to around 15 decimal places.  By default, MATLAB only prints five digits, but you can change this by typing format long and hitting RETURN.  Thereafter, MATLAB will print out answers to 15 significant digits (unless you go back to the default by typing format short).

Interrupting a Running Program:

You can interrupt a running program by pressing Ctrl-c at any time.

2. Matrices

To enter a vector

Separate the elements of a row with blanks or commas

b=[1 2 3]  

b =

     1     2     3  

b=[1, 2, 3] 

b =

     1     2     3  

 

 To enter a matrix:

 

Use a semi-colon to indicate end of each row

Use [ ] to enclose all elements of matrix

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

A =

     1     2     3

     4     5     6

     7     8    10  

B=[10 9 8; 7 6 5; 4 3 2]    

B =

    10     9     8

     7     6     5

     4     3     2  

Addition and Subtraction of matrices: Addition and Subtraction of matrices is defined just as it is for element-by-element.

 

Ex: X= A + B gives us X matrix as a result of addition of A and B matrices.

 

X= A + B  

X =

    11    11    11

    11    11    11

    11    11    12  

Y = A –B gives us Y matrix as a result of subtraction of A and B matrices.

Y = A-B 

Y =

    -9    -7    -5

    -3    -1     1

     3     5     8  

Addition and subtraction require both matrices to have the same dimension, or one of them to be a scalar ( a scalar matrix is a 1-by-1 matrix) . If the dimensions are incompatible, an error results.

Transpose of a matrix: Matlab uses the apostrophe (or single quote) to denote transpose. Transposition turns a row vector into a column vector.

X= B' 

X =

    10     7     4

     9     6     3

     8     5     2  

gives us the matrix X which is the transpose of matrix B.

Multiplication: Matlab uses a single asterisk to denote matrix multiplication. Rectangular matrix multiplications must satisfy the dimension compatibility conditions.

C=A*B 

C =

    36    30    24

    99    84    69

   166   141   116  

 

Identity matrix: Generally accepted mathematical notation uses the capital letter I to denote identity matrices. In Matlab, the function eye (m, n) returns an m-by-n rectangular identity matrix and eye (n) returns an n-by-n square identity matrix.

eye(4) 

ans =

     1     0     0     0

     0     1     0     0

     0     0     1     0

     0     0     0     1  

 

Inverses and Determinants: The inverse of a matrix is computed by the function inv and the determinant by the function det.

D= det (A) 

D =

    -3  

  X= inv (A) 

X =

    1.7778   -0.6667    0.1111

    0.4444    0.3333   -0.2222

   -1.2222    0.3333    0.1111

 

A*X

 

ans =

    1.0000         0   -0.0000

         0    1.0000         0

         0         0    1.0000  

 

Matrix powers: If A is a square matrix and ‘p’ is a positive integer, then A^p multiplies A by itself ‘p’ times.

A.^2 

 

ans =

     1     4     9

    16    25    36

    49    64   100  

A^2  

ans =

    30    36    45

    66    81   102

   109   134   169  

Eigenvalue: An eigenvalue and eigenvector of a square matrix A are a scalar l and a vector v that satisfy

An=ln

A=[1 1 1; 2 3 4;5 2 8] 

 

A =

     1     1     1

     2     3     4

     5     2     8  

 

lambda = eig(A)  

 

lambda =

   10.1098

    0.8902

    1.0000  

 

3. Solution of linear systems

 

      For example, we have the linear systems as following:

We can get the result from two ways.

A=[1 1 1; 2 3 4;5 2 8]  

 

A =

     1     1     1

     2     3     4

     5     2     8  

b=[3 ;8; 10]  

b =

     3

     8

    10  

x=inv(A)*b  

x =

    1.1111

    1.7778

    0.1111  

 

x=A\b  

 

x =

    1.1111

    1.7778

    0.1111  

  Case studies of Metabolic Flux (see BioE 494, Fall 2005, Lab_1)

4. Polynomials

Matlab provides functions for standard polynomial operations, such as polynomial roots, evaluation, and differentiation. In addition there are functions for more advanced operations, such as curve fitting and partial fraction expansion

Representing Polynomials:

Matlab represents polynomials as row vectors containing coefficients ordered by descending powers. For example, consider the equation

P(x) = x3 – 2x –5

To enter this polynomial into Matlab, use

p=[1 0 -2 -5] 

p =

     1     0    -2    -5  

Polynomial roots:

The roots function calculates the roots of a polynomial.

r = roots(p) 

 

r =

   2.0946         

  -1.0473 + 1.1359i

  -1.0473 - 1.1359i  

By convention, Matlab stores roots in column vectors. The function poly returns to the polynomial coefficients.

p2 = poly(r ) 

 

p2 =

    1.0000         0   -2.0000   -5.0000  

 

poly and roots are inverse functions.
 
 

Polynomial evaluation:

The polyval function evaluates a polynomial at a specified value. To evaluate P at x= 5, use

polyval (p, 5) 

 

ans =

   110  

Convolution and Deconvolution:

Polynomial multiplication and division correspond to the operations convolution and deconvolution. The functions conv and deconv implement these operations.

Consider the polynomials a(s) = s2 + 2s + 3 and b(s) = 4s2 +5s +6. To compute their product,

a= [ 1 2 3 ]; b= [ 4 5 6];  

c= conv(a,b) 

c =

     4    13    28    27    18  

Use deconvolution to divide a(s) back out of the product:

[ q, r] = deconv(c,b) 

q =

     1     2     3

r =

     0     0     0     0     0  

5. Ordinary Differential Equations(ODEs)

A system of linear, constant coefficient, ordinary differential equations can be written

dx/dt=Ax

where x = x(t) is a vector of functions of t and A is a matrix independent of t. The solution

can be expressed in terms of the matrix exponential,

x(t)=eA tx(0)

The function

expm(A)  

computes the matrix exponential. An example is provided by the 3-by-3 coefficient matrix

 A= [0,-6,-1; 6,2,-16;-5,20,-10] 

A =

     0    -6    -1

     6     2   -16

    -5    20   -10  

and the initial condition, x(0)

 x0= [1;1;1] 

x0 =

     1

     1

     1  

X = [];

for t = 0:.01:1

   X = [X expm(t*A)*x0];

end  

plot3(X(1,:),X(2,:),X(3,:),'-o')  

 

Numerical solver

These are the MATLAB initial value problem solvers. The table lists the kind of problem

you can solve with each solver, and the method each solver uses.

Solver

Solves These Kinds of Problems

Method

ode45

Nonstiff differential equations

Runge-Kutta

ode23

Nonstiff differential equations

Runge-Kutta

ode113

Nonstiff differential equations

Adams

ode15s

Stiff differential equations and DAEs

NDFs (BDFs)

 

function dy = vdp1000(t,y)

dy = zeros(2,1);    % a column vector

dy(1) = y(2);

dy(2) = 1000*(1 - y(1)^2)*y(2) - y(1);  

 

[T,Y] = ode15s(@vdp1000,[0 3000],[2 0]);  

plot(T,Y(:,1),'-o')  

 

 

6. Working in an M-Book

The document you are currently reading may look like an ordinary Microsoft Word® file, but there's one important difference.  It's been enabled to transmit commands in an input cell directly to MATLAB and have the output appear immediately in the document in an output cell.  Such a document is called an M-book.  In an M-book, if you want to redo a command, you simply edit the cell in which it appears and re-evaluate the cell. To convert a line of text in an M-book into an input cell, you can either hit CONTROL-RETURN while the cursor is on that line (this not only creates a one-line cell but evaluates it immediately), or else highlight the text and type ALT-N-I, or else use the Notebook menu at the top of the Word window and click on Define Input Cell.  (You need one of the last two methods if you want to create a multi-line input cell.)  Input cells are identified by black surrounding brackets and the fact that they are set in green Courier type.  Here is a typical input cell:

syms x

factor(x^2-4) 

ans =

(x-2)*(x+2)  

Try evaluating it by positioning the cursor in the cell and hitting CONTROL-RETURN.  Note MATLAB creates a blue output cell in response.  In this output cell you see exactly what MATLAB would respond had you entered your command in the Command Window.

7. Simple MATLAB Plots

The easiest way to plot a graph in MATLAB is with the command Plot.  What happens to the output from a graphics command such as this depends on whether you are working from Command Window or in an M-Book, so try it both ways.  If you execute the command from the Command Window (or change the Notebook Options… in the Notebook menu to turn off "Embed Figures in M-Book"), the output will pop up in a separate Figure Window.  On the other hand, in an M-Book with "Embed Figures in M-Book" turned on (that's the default), the figure will appear just below the command that produced it.  Go ahead and try evaluating:

x = -pi:pi/10:pi;  %Prepare your date

y = sin(x);     %Prepare your date

z = cos(x);

plot(x,y,'--rs',x,z,'-g*')

 

 

The command hold on sets a toggle switch so that output from the next plotting command is superimposed on the existing one.  The command hold off turns this off again. Thus to find the solutions of the equation sin(x) = x/2, you can superimpose the plots of sin(x) and of x/2 as follows:

hold on;

plot(x,x/2); hold off 

 

Note that you can separate commands on the same line with semicolons (or commas), though a semicolon will also suppress the printed output (not the graphical output) of a command.  Another important command for modifying plots is the axis command, which enables you to modify the scales on the axes.  For example, axis equal makes the scales on the horizontal and vertical axes the same. 

axis equal;

xlabel('x');

ylabel('sin(x)');  

 

 

The 3-D analog of the plot function is plot3. If x, y, and z are three vectors of the same length,

 

plot3(x,y,z) generates a line in 3-D through the points whose coordinates are the elements of x, y, and z and then produces a 2-D projection of that line on the screen. For example, these statements produce a helix.

 

t = 0:pi/50:10*pi;

plot3(sin(t),cos(t),t)

axis square; grid on  

 

8. Programming-M File

 

Data Type

 

Flow Control

There are eight flow control statements in MATLAB:

  • if, together with else and elseif, executes a group of statements based on some logical condition.
  • switch, together with case and otherwise, executes different groups of statements depending on the value of some logical condition.
  • while executes a group of statements an indefinite number of times, based on some logical condition.
  • for executes a group of statements a fixed number of times.
  • continue passes control to the next iteration of a for or while loop, skipping any remaining statements in the body of the loop.
  • break terminates execution of a for or while loop.
  • try...catch changes flow control if an error is detected during execution.
  • return causes execution to return to the invoking function.

All flow constructs use end to indicate the end of the flow control block.

 

9. Getting Help in MATLAB

 

To use MATLAB effectively, it's important to know how to look up the syntax for hundreds of commands that you can't possibly memorize.  There are many ways to get online help.  If you remember the name of a command, but can't remember its syntax or all its options, all you have to do is  Click Help Menu, Go to the Using the Desktop.