Matlab Assistance
The followings are examples using Matlab commands and program scripts to help you with the typical programs that you will run in this course. You may click on the appropriate topic, or scroll down through this page.

*

Arrays
Plotting
If Function
For-Loop, Matrix Manipulation
Printing
ODE45 Function
Getting help in Matlab


Arrays

The first example shows how to define and manipulate arrays in Matlab. To create an array, enter each element (separated by a space) between brackets, and set it equal to a variable. For example, to create the vector a, enter into the Matlab command window (you can "copy" and "paste" from your browser into Matlab to make it easy): Matlab should return: Let's say you want to create an array with elements between 0 and 10 evenly spaced in increments of 2 (this method is frequently used to create a time vector): Manipulating arrays is almost as easy as creating them. To square each component in the array, you have to use ' .^ ' instead of ' ^ ' as shown: Suppose you would like to add 2 to each of the elements in 'a'. The equation for that looks like: Now suppose, you would like to add two arrays together. If the two are the same length, it is easy. Simply add the two as shown below:

Plotting

It is also easy to create plots of results. If you wanted to plot a cosine wave as a function of time. First make a time vector. The semicolon after each command line causes the data not to be printed to the screen. Compute the cosine value at each time. You can also add things such as a title and labels to your plot.
%
%   Matlab example program #1
%   

clear all;

t=0:0.25:10;
y = cos(t);
plot(t,y); 
title('Matlab example #1');
xlabel('time (sec)');
ylabel('y');
grid;
Basic plotting is very easy in Matlab, and the plot command has extensive add-on capabilities.

For instance, you can plot multiple curves in different colors.

For a more complete Matlab tutorial on plotting see plotting tutorial. This page provides a good reference in general.


If Function

The next example focuses on using ' if ' function .
%
%   Matlab example program #2
%   

clear all;

x = 0:0.05:10;

a = input ('a = ');

%
%   Check for  'a'
%
%   -10 <= a <= 10 --> c = 2
%   a < -10 or a >10  --> c = -2
%   

if -10 <= a & a <= 10

  c = 2;

elseif a < -10 | a > 10

  c = -2;

end
 
%
%   Check for  'a'
%
%   a = 0  -->  b = 0
%   a is not zero  --> b = 1
%   

if a == 0

  b = 0;

elseif a ~= 0

  b = 1;

end

z = b*sin(x)+c*cos(x).^2;

figure(1); clf;
plot(x,z); 
title('Matlab example #2');
xlabel('time( sec)');
ylabel('z');
grid;

For-Loop, Matrix Manipulation

The third example is for how to use for-loop, matrix manipulations.
%
%   Matlab example program #3
%   

clear all;

for i = 1:2
  for j = 1:2

    x(i,j) = i*j^2;

  end
end

z = x^2;

Z = z'

Printing

The following steps show you how to print in Matlab.

Macintosh
Windows Unix

ODE45 Function

ODE45 is used to solve linear or non-linear differential equations. This is done with a 4th and 5th order Runge-Kutta method to integrate the equations. NOTE - you DO NOT have to understand 4th and 5th order Runge-Kutta method to use ODE45 solver, check a numerical methods book if you are interested. You will only need to know the parameters to run the routine.

ODE45 has a typical form to use.

tspan = [t_start, t_final];
X0 = [x0, xdot0];

options = odeset('Refine',6,'RelTol',1e-4,'AbsTol',1e-7); 

[T, X] = ode45(F, tspan, X0, options);

T in the left bracket is for time.
X is our main variables, in vector form.
F in the right side is a name of the subprogram for ODE45 solver
        which will be explained in detail a little bit later).
tspan is the time period that you want to calculate, which consists of
        start time and end time.
X0 contains the initial conditions for ODE variable, x0 = x(0), xdot0 = xdot(0).
options is the command that you can adjust the performance of ODE45 
        solver.
        
There are many options you can choose from, type 'help odeset' at the 
Matlab command line.
'Refine' controls the number of data points for ODE solver.
The higher the number after 'Refine' is more data points there are, but the
slower the calculation is.
'RelTol' controls the relative error tolerance and 'AbsTol' controls
the absolute error tolerances.
The following is an example of a pendulum problem which illustrates the use of ode45.
%
%   Matlab example program #4
%

The first few lines are for constant input values like mass of the 
bar, etc.  The numbers given are all arbitrary.

m = 1;                      %  mass of the bar
g = 9.806;                  %  acceleration of gravity
l = 1;                      %  length of the bar

tspan = [0,5];              %  time duration for calculation
Now, plug in the initial conditions for main variable, theta in this case, the rotation angle of bar.
theta = 1e-4;               %  initial displacement of the bar
theta_dot = 0;              %  initial angular velocity of the bar
Note here there is a non-zero initial displacement (disturbance) and a zero initial velocity.
x0 = [theta,theta_dot]; 

options = odeset('Refine',6,'RelTol',1e-4,'AbsTol',1e-7); 
  
%  'Refine' was used to produce good-looking plots
%  default value of Refine was 4.  Tolerances were also tightened.
%  scalar relative error tolerance 'RelTol' (1e-3 by default) and 
%  vector of absolute error tolerances 'AbsTol' (all components 1e-6 by
%  default).
'Refine' option does not apply if time span is more than 2. After we specify all the inputs for ODE45 solver, we write
[t,x] = ode45('pend_sol',tspan,x0,options);

% Note that the equations of motion in state space form are in a subprogram
named pend_sol
After finishing the calculation, you plot them. Here are some of the plotting commands.
figure(1); clf;
plot(Theta*180/pi,Theta_dot,'b');  
title('Pendulum problem');
xlabel('Displacement (degrees)');
ylabel('Angular velocity (radians/sec.)');
mx_theta_dot = max(Theta_dot);
axis([0 360 0 1.1*mx_theta_dot]);  grid;
Here, "pend_sol" is the name of the subprogram and it is shown below. You must create a separate file for the subprogram with the same name you gave in the main program under the same folder/directory.
function xdot = pend_sol(t,x)

%   Constants and input variables

g = 9.81;            %  gravity (m/s^2)
l = 1;               %  length of the bar

%   State variables

x_dot1 = x(2);
x_dot2 = (3*g)/(2*l)*sin(x(1));

xdot = [x_dot1; x_dot2];  % end of subprogram.
The first line is for declaring the subprogram. Array xdot is for a derivative of array x, so xdot(1) is a derivative of x(1), an angular velocity and xdot(2) is an angular acceleration. You just write that down in the program as above. For a state space derivation tutorial click here.


Getting help in Matlab

Matlab has very good help page in itself. Just type ' help {topic} ' at the Matlab prompt and you would get instructions for the topic you want. For example,
help plot
will give the instructions on how to use ' plot ' command.

If you need help getting started with Matlab, go to Getting Help with Matlab and .m files

Another good resource is the Matlab Basic Tutorial Web page, which is part of the Controls Tutorials for Matlab.


Return to ME240 Homepage