__Matlab Session 1__

Matlab is a program for performing numerical computations, very popular amongst engineers, scientists and mathematicians. It is sold by Mathworks It is particularly useful, in my opinion, for:

- Plotting data
- Numerical analysis of data
- Solving systems of equations (algebraic of differential) numerically
- Modeling of dynamic systems
- Control system design

There are plenty of basic Matlab tutorials out there:

Mathworks Basic Matlab Tutorial

Practice Problems which use
these concepts can be downloaded in PDF form:

Start Matlab by going to the Start menu and finding Matlab 7.1 (or whatever version you have.) You should see a window pop up that looks like:

The various parts of the window are:

The “Command Window” is where you type in commands… it acts
just like a calculator. The Matlab
commands *help* and *lookfor* are particularly useful for
finding stuff out. Try them out. *lookfor*
searches help files So, if you wanted to do something with fuzzy logic, try *lookfor fuzzy* and it will tell you a
bunch of functions. Then pick one that
sounds useful and type *help
<whatever>* and it will tell you more about that function. See below:

You can define variables and do operations on them just like on a calculator. The “workspace” area on the top left will show you all your currently defined variables.

One thing you will want to do early on is change the working directory. Matlab defaults to a directory under the Matlab main directory. You probably want to work in a subfolder of your home directory. Change your working directory by mousing the path bar at the top of the screen, as shown in the top image on this page. You can click the three dots icon to the right of that path bar to browse to your favorite working directory. This is the directory Matlab will save and load data files from and look for user defined functions in.

There are many many many useful functions in Matlab that do everything from basic arithmetic to control system design to image processing. In many ways, being good at Matlab means knowing a ton of useful functions. Go look in the help menu to see the wealth of things available to you.

You define vectors in Matlab with the syntax:

>> v=

Which is a row vector, or

>> v=

Which is a column vector. Vector multiplication is defined according to normal linear algebra rules… so a 3x1 vector times a 1x3 gives you a 3x3 matrix and so on. See example below.

Matrices can be defined similarly, separating rows with semicolons and columns with spaces:

>>A=

You can multiply matrices and vectors just like
scalars. You can also use complex
numbers by using the built in constants *j*
and *i.
pi* is also a built in constant.
See some examples below:

Also notice here the scientific notation Matlab uses. After I multiply A*A (matrix multiplication),
it reports the answer with 1.0e+002 at the top… meaning that everything in the
matrix is multiplied by 100. Hence,
A(1,1) is *6+3i.*

If you want to perform an arithmetic operation element-by-element, rather than doing true vector or matrix mathematics, use the operator with a dot in front of it. What I mean is,

Be careful you are doing what you mean to do. Often in matlab a vector is really a list of scalars (say from data you gathered in the lab) and you may want to, say, multiply the corresponding samples in the two channels of data together. You would then use the .* operator, not the * operator. The Matlab window showing the above operations compared is shown below:

One thing that Matlab is useful for is plotting data. In the Matlab window below I will plot a sine
function, by first creating a vector of time values *t*, which goes from 0 to 1 and has 1000 points. (I use the *linspace* function, which generates a linearly spaced list of
values. Type *help linspace* for more information.) I then define a vector *x* which is equal to *sin(4*2*pi*t)*. **Notice
that I put a semicolon after the commands for creating t and x. **This tells Matlab to just perform the
operation, but not report the result. If
I had left the semicolon off, then a thousand values will scroll past me,
making a big mess. You can put a
semicolon at the end of any command to tell Matlab to be quiet and not report
the result. After defining

The following figure window pops up.

You can copy Matlab figures to the clipboard from the edit menu in the figure window, save them to Matlab figure files or to image files of various types (eps, jpeg, etc.) for including in documents. You can also edit all the properties (such as axis labels, font, line color, width, and style, and so forth) by selecting the items in the window using the arrow tool, right clicking, and changing properties. You can zoom in using the magnifying glass tool, and zoom back out by double clicking with the zoom tool.

Another thing I can do in Matlab is compute derivatives and
integrals numerically. The *gradient* function computes numerical
derivatives, and the *cumtrapz* uses
the trapezoidal rule to cumulatively integrate a signal. Type *help
gradient * or *help cumtrapz* for more information.
See the example below:

Where I have done a couple of new
things. The gradient function needs the
data (*x)* and the spacing between data
points (*1/1000 in this case)*. The cumtrapz function needs the data (*x*) and the thing to integrate with
respect to (*t*). The *hold
on* command tells Matlab to hold the plot, so that when I do the next plot
commands it keeps my original sine curve on there. If I didn’t say *hold on*, Matlab would just wipe out the original curve when it
plotted the new one. In the *plot* commands, I have included a string
which tells what color to make the line *‘r’
* for red, and *‘g’* for green (see *help plot *for
more information). This generates the
following figure:

Where the derivative is in red and the integral in green. Since the frequency of this sine curve is 4pi, the derivative is larger amplitude than the original signal and the integral is smaller amplitude (it looks flat, but if I zoom in, you can see that it is also a cosine wave as it should be):

If you just want to compute the
definite integral of a signal, you can do so using the *trapz* command, which uses the trapezoidal rule. For instance, to find the total integral of
the original sine wave I could do the following:

Which is very close to zero. The 2e-17 value produced is a numerical error due to the numerical nature of the computation. Expect to see such things in Matlab… most everything is done numerically.

__Matlab Session 2__

In the Matlab session taught Feb 13-15, 2006, I attempted to rapidly go through:

**1. **__M-files__

These are scripts which contain a
sequence of Matlab commands. They
operate exactly the same way as typing the commands one after the other at the
Matlab prompt. They are created by going
File|New|M-file, which will bring up the Matlab editor. Save the file wherever you like. It is simply a text file with a *.m* extension. They can be edited by any program which reads
text files, although the Matlab editor is probably best since it
highlights/colorizes the text appropriately.
You can run a m-file from the Matlab command prompt by typing the name
of the file (without the *.m* extension). It will operate just like any other Matlab
command. Make sure your working
directory is set to the directory that the m-file is in, or Matlab won’t find
it!!

In the Matlab editor, type all the commands you want and then save the file. You can run it from the Matlab prompt. For example, let’s say we wanted to create an m-file to solve the quadratic equation:

*Ax ^{2}+Bx+C=0*

The quadratic formula, as you recall, is:

But you want to handle the case
where A=0 differently or you will get a divide by zero error. Below you can see an m-file I wrote which
solves this problem. It is called *quadratic1.m*.

If you save it in the working directory and run it, you should see:

Let’s say we wanted to include a for loop to let A=-5,-4,-3…5, and plot all the roots of the quadratic equation for each of these values. We could do this using the following m-file:

If I run quadratic2 at the Matlab prompt, I see the following figure appear:

Where we can see the two real roots for A<0, the single root x=-1.5 for A=0, and then the complex conjugate pairs moving off the real axis for A>0.

These two m-files give examples of
how to use *for *loops and *if* statements. NOTE:
mfiles are exactly like typing at the command prompt; hence if you alter a workspace variable in
your mfile, it will change it in the workspace.
Similarly, workspace values are available to your mfile.

**2. **__Functions__

Functions are similar to m-files, but there is a well-defined input and output interface. A function takes arguments and returns something. It can take multiple scalar, vector, or matrix arguments, and return any number of things as well. Type

>> help function

At the Matlab prompt for more information. As an example, I can set up my quadratic equation solver as a function in the following way:

Some important things to note about functions:

(1) The
filename for the function must be the same as the function name (here, both are
*quadratic*)

(2) The
function has a “local scope”… it does NOT have access to variables in the
workspace. If you want it to have access
to workspace variables, you must define the variables as global both inside the
function and in the workspace (*>>
help global *for more information).

So, if I run this function at the Matlab prompt, I will see:

**3. **__Solving
systems of algebraic equations__

Matlab can be used to solve systems of algebraic equations. For linear systems, the system can be set up in the form:

*Ax=b*

Let’s say we wanted to solve the set of linear algebraic equations:

*-a + 4b -6c = **pi*

*8a + b = 2*

*cos(**pi/6)**a –e ^{2.3}c
= 0^{}*

We can set this up as a matrix
equation and use the Matlab backslash operator to solve. (*>>
help slash*) See the result below:

So, here, *a=0.1449, b=0.8405, c=0.0126.*

A set of nonlinear algebraic
equations can be solved using the Matlab *fsolve*
function. In order to solve the set of
equations, a function must be defined (see part 2 above on how to make
functions) which defines the set of equations in the form:

Let me illustrate with an example. Let’s say I wanted to solve:

Which graphically looks like:

I would set the system of
equations up in a function called *myfun.m*
(or whatever I like), which looks like:

And then if I use fsolve to solve this system in the Matlab command window, I can find the two solutions using two different initial guesses (refer to the graph above to see what’s going on graphically):

Where I found solution #1 (*x=0.0363, y=1.2245)* when I used the
initial guess *x=1,y=1. *I found solution #2 (*x=-0.4815, y=-1.1765)* when I used initial guess *x=-1,y=-1*.

**4. **__Solving
systems of ordinary differential equations__

Systems of nonlinear ordinary
differential equations (ODEs) can be solved in a very similar fashion. First, we have to define the system of ODEs as
a system of __first order__ differential equations (note that an N^{th}
order ODE can always be expressed as N first order ODEs) in the form:

Where *x* with a dot over it indicates one derivative with respect to
time. Again, let me illustrate with an
example. Let’s say we wanted to solve
the nonlinear Duffing oscillator (cubic spring) equation subject to harmonic
forcing:

Which can be written as two first order ODEs in the above canonical form:

A Matlab function which defines this ODE is shown below:

Note that the last line

xdot=xdot’;

Simply transposes the vector xdot, because the ode45 function that I am about to use requires a column vector to be returned, not a row vector, and xdot turned out to be a row vector.

Now that the system is defined, we
have a choice of many solvers to use which may be appropriate for certain kinds
of numerical problems (>> *help
ode45*). One solver which I commonly
use is ode45 which is a “medium order method for solving non-stiff ODEs”
(according to the help file). The syntax
requires a time span to solve over, and initial conditions for each of the
variables. There are many other options
(see the help file). The solution to the
above system is computed on the time interval *t= [0,1]* with initial
conditions

The plot of the solution looks like:

**By looking at these examples, you should be able to
write Matlab m-files and functions, and solve systems of linear and nonlinear
algebraic and differential equations.
Don’t be shy about using the Matlab help function, help menu, google,
and the large number of web tutorials at your disposal. Matlab is a powerful program which will serve
you well for many computing needs in the future. **

Practice Problems which use
these concepts can be downloaded in PDF form:

**Happy Matlab-ing!!!**