RTM Matlab Intro
RTM Matlab Intro
As you may have heard, MATLAB is a powerful platform for mathematical and scientific computation.
Compared to C or JAVA, it has an easy to use programming interface and many, many built in functions
to do tons of different things. If you can learn its syntax and language now, it will pay off greatly for
you in the future. Well take you through an overview of its usage, and then focus on certain areas that
youll be likely to run into sooner rather than later.
Entering Data
On the surface, MATLAB is a huge, expensive, glorified, calculator. Everything (well, mostly) in
MATLAB is created and treated as a matrix (MATLAB is short for MATrix LABoratory). MATLAB has the standard arithmetic operators that youd expect: +, , , , and exponentiation, .
So entering
>> 5+6
This returns 11, as you would hopefully expect. To suppress the output (e.g you dont want to see
the result), end your command with a semicolon. To enter a vector, put the input in brackets. For
instance, to create a row vector in R4 , you could enter:
>> A=[4,1,5,6];
1
We have just assigned the vector [4, 1, 4, 6] to the variable A. MATLAB is case sensitive, so the
variable a6=A. If you wanted to make that a column vector, just use semicolons instead of colons,
or transpose the vector using the operator. To enter a matrix, stick some rows together. For
example, a 2 2 matrix B could be entered as:
>> B=[1 2; 3 4]
1 2
3 4
Some vectors would be unpleasant to type in all of their glory, and MATLAB understands that.
For example, to obtain the vector t = [0 .5 1 1.5 2 . . . 9 9.5 10], you would type t=[0:.5:10], which
creates a vector from 0 to 10 in half increments. Or, to get a vector containing equally spaced
entries, you can use the linspace command. For example, to get 400 linearly spaced entries from
0 to 100, you could type >> r=linspace(0,100,400). Some special cases:
A scalar does not need brackets. g=9.81; will suffice.
Square brackets with no elements (X=[]) creates a null matrix. Can be useful to delete
rows/columns of a matrix. Example: if you wanted to delete the 4th row of matrix A, you
could say A(4,:)=[];
Since everything in MATLAB is a vector or a matrix, it makes sense to be able to extract data from
certain points of a vector. For instance, to obtain the 5th entry of a vector r, type >> r(5). For a
range of values, say from a to b, type >> r(a:b). For a matrix, the syntax is (row, column). So
to get the i, j entry of the matrix B, type >> B(i,j). Similarly, you can pull out ranges of values
as you could with a vector. If you wanted the entire range of rows, or columns, use the colon. So
the rowspace of the fourth column of A would be A(:,4).
Operations
Youll be pleased to know that the standard operations, sin, cos, tan, arctan, log, ln, and exp (all
are not listed here) exist in MATLAB. You can apply these to vectors, matrices, whatever. If you
wanted the sine of a vector, just do b=sin(a). Some things to know:
The log command is the natural log. For log10 , use log10.
e is not a protected operator. If you want e5 , use exp(5).
MATLAB recognizes i and j as the imaginary unit.
Matrix multiplication works as youd expect, so long as the dimensions match of course. To
multiply 2 matrices A, B just do >> C=A*B. MATLAB can also do element wise operations
on matrices and vectors using the dot notation. For example whereas >> C=A*B is standard
matrix multiplication, >> C=A.*B will create a matrix C whose elements are defined as cij =
aij bij . The dot notation works with multiplication, *, division, /, and exponentiation. Youll
have to use this more often than you think.
1 1 1 0 0
1 1 1
0 0 0
0 0 0
Exercise:
0 0
0 0
.
4 0
0 4
1 2 3
A = 4 5 6 ,
7 8 9
1 2 1
B = 0 1 0 ,
4 5 9
"
C=
1 0
0 1
Try some of these basic operations and see what happens: A B, A. B, 2 + A, A + B. Now create
a vector and a matrix with the following commands: v=0:0.2:12; M=[sin(v); cos(v)];. Find
the sizes of v and M using the size command. Extract the first 10 elements of each row of the
matrix and display them as column vectors.
More on Plotting
Lets take a moment to delve a little more deeply into the art of generating plots in MATLAB. We
can do a lot with our plots: we can change the linewidth, change the color, change the fonts (and
size) of the titles, use LATEX notation, and much more. You can either do this via the user interface,
or on the command line.
LineWidth. To increase the thickness of the traces on the plot, add in the LineWidth option:
plot(x,y,LineWidth,2). This will plot with a line width of 2.
Changing Fonts. You can probably tell what is going on by this example:
title(My Awesome Plot,FontName,courier,FontSize,20,FontStyle,bold);.
The font will be Courier, at size 20, bolded. Substitute your favorite in as you so desire.
LATEX Inclusion. MATLAB, by default uses TEX to render the axes and titles, which can be
inadequate when were used to using LATEX characters. To get around this, we need to specify
the LATEX interpreter. If I wanted to have
u
t
2
1
1
0.5
0
0.5
0.5
0.5
0.5
0.5
z=sin(x)+cos(y);
plot(t,z);
axis([0 2*pi -2 2]);
subplot(2,2,3)
z=sin(x).*cos(y);
plot(t,z)
axis([0 2*pi -1 1]);
subplot(2,2,4)
z=(sin(x).^2)-(cos(y).^2);
plot(t,z);
axis([0 2*pi -1 1])
subplot(m,n,i) creates an m n array of plots, and then you count through them with i,
counting from left to right, top to bottom. Each subplot is rendered independently of the
rest.
Surface and 3D plots. There are two types of R3 plots in MATLAB, surface plots, and line
plots. An example of a line plot is given in the next exercise where you plot a helix. Some
examples of surface plots are mesh, surf, surfl, waterfall, and there are more. To really
use these plotting tools, youll need to know about meshgrid. meshgrid transforms vectors
into arrays so that you can evaluate functions in R2 and plot them with these commands.
Compare the plots below:
Mesh Plot
Waterfall Plot
!2
!2
!4
!4
!6
50
40
!6
50
40
20
20
0
Surf Plot
Meshz
!2
!2
!4
!4
!6
!6
50
40
50
40
20
20
0
x=linspace(-3,3,50);
y=x;
[x,y]=meshgrid(x,y);
z=-5./(1+x.^2+y.^2);
subplot(2,2,1)
mesh(z); title(Mesh Plot)
subplot(2,2,2);
waterfall(z); title(Waterfall Plot);
hidden off;
subplot(2,2,3);
surf(z); title(Surf Plot);
subplot(2,2,4);
meshz(z); title(Meshz);
Lastly, to export your figures for use in LATEX and other nice programs, be sure to save the
figures as EPS format. This way, you can use them in your TEX documents with no problem at all.
Exercise:
Plot the sine and cosine functions on the interval [0, 2] on the same graph. Use
different colors and line styles for each trace, and label all aspects of the plot. Investigate and use
the legend command. Also, MATLAB can also plot 3D data with the plot3(x,y,z) command.
Try and use this command to plot the standard helix, where x(t) = sin(t), y(t) = cos(t), z(t) = t
on the interval t [0, 20].
Functions can take dynamic inputs, but all variables are local to the function and are not
explicitly saved in the workspace when complete.
Why is this important? Well talk about it. To write an m-file, you can either use your favorite
text editor on your computer or (even better) the builtin MATLAB file editor. To get started, you
can either click the new file button in the main MATLAB window, or type >> edit myscript,
(myscript being whatever you want to call your new m-file) and then you can go from there. Also,
anything behind an % is a comment and is thusly ignored by MATLAB. Comment your code as
much as you can! Here is an example of a script that plots the unit circle:
% CIRCLE - A script to draw the unit circle
% ----------------------------theta=linspace(0,2*pi,100);
% create a vector
% generate y-coords
plot(x,y,0,0,+);
Exercise:
Turn the circle.m script file above into a function that accepts an arbitrary radius r,
For Loops
There are two kinds of loops well use: for and while loops. A for loop is used to repeat a
statement of a group of statements for a fixed number of times. An example:
for m=1:100
num = 1/(m+1)
end
This will print out the value of
1
m+1
given by an explicit increment, like for i=m:k:n, to advance the counter i by k each time. You
can have nested for-loops, but each must match with its own end.
While Loops
A while loop is used to execute a statement or a group of statements for an indefinite number of
times until the condition specified by while is no longer satisfied. An example!
% find all the powers of 2 below 10000
v=1; num=1; i=1;
while num < 10000
num = 2^i;
v = [v; num];
i = i+1;
end
Once again, a while loop needs a matching end statement.
If Statements
Frequently youll have to write statements that will occur only if some condition is true. This
is called a branch statement. Typically youll have an if statement, and if it isnt satisfied, a
corresponding else or elseif statement.
Along with the standard greater than, and less than conditions (a>b, b<a, a>=b, b<=a), there
are also:
and: a & b
or: a | b
not-equal: a ~= b
9
Debugging Output
Sooner or later, youll have to debug your code. One thing that may help in this endeavor is the
disp() command. disp() merely displays its input to the command window. Try >> disp(Hello
World!);. Sticking a disp on key lines of your program can help you trace where MATLAB is
when it gets stuck. Other useful commands in this department:
num2str(): converts a double number to a string. If you want to display a number in a
string, youll need this function.
str2num(): goes the other way. Useful for when you import strings of number from a file. In
order to do anything with them, they have to be converted to doubles first.
10
Exercise:
Multiply all elements by 100 and then round off all elements of the matrix to integers using
the fix command.
Replace all elements of A < 10 with zeros.
Replace all elements of A > 90 with infinity (inf).
Extract all 30 aij 50 in a vector b, that is, find all elements of A that are between 30
and 50 and put them in a new vector.
Next, simulate a random walk. Say someone can walk right or left. They flip a coin. If heads, they
take a single step right, tails they go left. The individual does this 5000 times. Can you plot the
path? What if the coin were weighted to one side? Welcome to Monte-Carlo simulations.
Linear Algebra
Since everything in MATLAB is a matrix, it makes sense that MATLAB would be well-suited to
linear algebra problems. For example, to solve the common problem Ax = b, where dim(A) =
n m, and x, b are vectors m long, you can simply type >> x=A\b. Consider the system:
5x 3y + 2z = 10
3x + 8y + 4z = 20
2x + 4y 9z = 9
Its coefficient matrix is
A = 3
2
8
4
4
9
And the known constant vector is b = [10 20 9]T . To solve this system in MATLAB:
>> A=[5 -3 2; -3 8 4; 2 4 -9];
>> b=[10; 20; 9];
>> x=A\b
x =
3.4442
3.1982
1.1868
11
Note that the backwards division operator is equivalent in usage to inv(A)*b. Some other useful
linear algebra related commands:
rref(C): finds the reduced row echelon form of the matrix C
inv(A): computes the inverse of the matrix A, assuming it exists.
det(A): finds the determinant of an n n matrix A.
[V,d]=eig(A): finds the n n matrix V whose columns are eigenvectors and D is an n n
matrix with the eigenvalues of A on the diagonal. Solves the problem Av = v.
Built-in matrix factorizations: [L,U]=lu(A), [Q,R]=qr(A).
diag(v): generates a diagonal matrix with vector v on the diagonal. diag(A) extracts the
diagonal of matrix A as a vector.
Solving ODEs
One of the more prolific problems that well deal with in MATLAB is numerically solving and
plotting systems of ordinary differential equations (ODEs). MATLAB can only solve first order
ODEs, so if you have higher order systems youll have to devolve them to first order equations;
well cover this below. The basic syntax for solving an ODE in MATLAB is:
[time, solution] = ode45(@odefun,[tspan],[ic],options,parameters )
where ode45 is one available solver (a 4-5 order Runge-Kutta Method), odefun is your ODE file
(more on this shortly), tspan is either an interval or a vector where the ODE will be solved, ic
is an initial condition vector, and options are ODE specific options, such as tolerances. Solving
most ODEs in MATLAB requires you to:
1. If the order is greater than 2, write the differential equations as a set of first order ODEs.
This just involves introducing some new variables.
2. Write a function to compute the state derivative. This function needs to return out the state
derivative x.
3. Call the solver, extract the desired variables, use knowledge to understand what is happening.
An introductory calculus class tells us that the solution to this is ex . Lets code this up and compare
it to the analytical solution. First thing first, we need to create our ode file. Here is one possible
example:
function dy = simpleode(t,y)
dy = y;
To solve this, call at the command line [t y]=ode45(@simpleode,[0,2],[1]). This solves the
function on the domain [0, 2] with an initial condition of y(0) = 1. To plot, call the plot command:
plot(t,y). Now plot ex along the same time steps and plot this on the same axis should be
the same thing. It may be worthwhile to compute the error between the ODE solution and the
analytical solution to see how accurate the solver is.
13
= 2 sin ,
(0) = 1, (0)
= 0.
To recast this equation as a system of two first-order equations that MATLAB can solve, we perform
a variable substitution:
Then, u1 = = u2 and u2 = = 2 sin(u1 ). To write the ODE file, it
Let u1 = and u2 = .
may help to see what this now looks like in vector form:
"
u1
u2
"
=
u2
2 sin(u1 )
Before we write the file, note that will have to be coded into the odefile or passed in as a
parameter. The former is easiest, so well code it so we can pass it in as a parameter:
function udot = pend(t,u,omega)
udot = zeros(2,1);
udot = [u(2); -omega^ 2*sin(u(1))];
To call and pass the parameter = 1.56, call like so:
>> [t, y]=ode45(@pend,[0 20],[1; 0],[],1.56);
The empty [] is a place-holder for ODE options. Were not using any here, hence the empty
brackets. Go ahead and plot the displacement and velocity vectors, and then construct a phase
portrait. As always, label and title your plots.
Increasing Resolution
By now you may have noticed that when you specific a time span in the solver, you get a seemingly
arbitrary number of data points in your solution vector. The number of points is far from arbitrary,
but rather is a result of the way the ODE solver works and the absolute and relative tolerances
in the solvers algorithm from the nth time step to the (n + 1)th time step. In fact, even if you
specify a time vector the ODE solver will still solve the ODE where it wants to, and then linearly
interpolate to your points. The only way to increase accuracy is to decrease the tolerance through
the ODE options.
The default tolerances are 1E-3 and 1E-6 for the relative and absolute tolerances. The fastest
way to get more data points is to decrease the relative tolerance to something smaller, like 1E-6:
>> options=odeset(RelTol, 1E-6);
14
You just now need to specify your options in your solver call (continuing previous example):
>> [t, y]=ode45(@pend,[0 20],[1; 0],options,1.56);
There are lot of other ODE options that will affect the performance, accuracy, and overall fidelity
of the solver. Type help odeset to see what all is available. For casual usage of ode45, the default
options are typically sufficient. By the way, if you dont assign any output variables to the solver
call, the solver will automatically display a plot with the solutions.
Exercise:
y 0 (0) = 0, y(0) = 1
which could model the transient response of an RLC circuit. Solve and plot the resultant functions.
If you want, compare the numerical approximation with an analytical solution (Maple may be
helpful in that endeavor), or even the accuracy of ode23 versus ode45.
Optimization Problems
One of the big problems well be doing this week is an optimization problem, specifically fitting
data to a model. Well go through a different problem, but use the same procedure so that the
coding wont be as difficult as it could be.
The basic, most general minimization problem is
min
x
f (x)
where is some domain where the solution lies. How to achieve this is the question. In many
cases, you want to optimize the problem subject to constraints, be they linear, non-linear, or even
PDE constrained. In this example, well just consider the unconstrained case.
A classic test example is the Rosenbrock banana function, f (x) = 100(x2 x21 )2 + (1 x1 )2 . To
see what this surface looks like, try this:
>> [x,y]=meshgrid(-3:.1:3,-3:.1:3); z=100*(y-x.^2).^2+(1-x).^2; surfc(x,y,z);
The minimum for the banana function is at (1, 1) and has value 0. We want MATLAB to automagically find it. First, write a function file that takes a vector input and outputs the function value
that you wish to minimize:
function fx = banana(x)
fx = 100*(x(2)-x(1)^2).^2+(1-x(1)).^2;
15
To find the minimum in this unconstrained case, well use fminsearch, which attempts to find the
minimum of a function, be it scalar, vector, or matrix valued. To use fminsearch, it needs only
the function name and an initial iterate where it should start to look. For this problem, lets start
looking in the neighborhood of (2, 3):
>> [x,fvalue]=fminsearch(@banana, [2 3]);
This returns an answer that says it found a minimum at (1, 1) with a function value of 2.718E 10,
which is more or less zero. fminsearch is an algorithim that is derivative free. It doesnt need
gradient information about the function in order to march along. Other algorithms, such as those
implemented in fmincon (constrained optimization) and fminunc either need or approximate the
gradient of the objective function. One last note: fminsearch and other algorithms can be very
sensitive to the initial iterate. Its possible to become stuck in a local minimum and get an answer
that is non-sensible. If this happens, just start looking somewhere else.
X
(ymodel ydata )2
data =
.44
3.09
22.82
3.67 75.35
3.19 44.67
2.46 33.55
.767
2.57
2.38
where the first column is your x data, and the second column is the y data. Here is one way we can
obtain the best-parameter values (that is, the best a, b, c to minimize J): Write a cost function that
computes the error between the data and the model for a given q = [a b c]T , and then minimize
the cost using one of the algorithms. Here is my program that computes the cost:
16
function J = parab(q);
a=q(1); b=q(2); c=q(3);
data=[-.44 3.09;
2.38 -22.82;
-3.67 -75.35;
3.19 -44.67;
-2.46 -33.55;
.767 2.57];
xdata=data(:,1);
ydata=data(:,2);
ymodel=a*xdata.^2 + b*xdata + c;
J=sum((ymodel-ydata).^2)/2;
Now, we just minimize J to obtain the parameters. I minimized with fminsearch, though
other non-sampling algorithms will work here too. My result was a parameter vector of q =
[5.43 1.83 4.35]T and a final cost function value of 0.7055. When I plot the data with the
parabola generated by q, here is what it looks like:
Data and Model Comparison
10
Model
Data
0
10
20
30
40
50
60
70
80
90
4
17
18