# BASIC MATLABSIMULINK FOR SYSTEM DYNAMICS

Document Sample

```					BASIC MATLAB/SIMULINK FOR SYSTEM DYNAMICS
Brief notes for ME 3281
W. Durfee

What is Matlab? Language for technical computing. For math and computations.
Excellent graphics. Fast, easy to use. Prevalent in industry. Based around arrays; vectors
and matrices. Matrix Laboratory Much of system dynamics analysis rests on linear
algebra so Matlab is a natural. Toolboxes are application-specific wrapper functions.
Statistics, control design, image processing, filter design, system identification…
Excellent graphics, line-plots to 3-d contour plots. The package of choice for data
visualization. Can also do symbolic math, like Mathematica.

What is Simulink? A graphical front-end to Matlab. Simulation of linear and non-linear
systems. Block-diagram oriented, point-and-click interface. Easy to use. A natural for
simulating control systems. Good for nonlinear and sampled-data (computer) control
system simulation.

Matlab/Simulink is available in IT labs. Can purchase Student version Matlab/Simulink,
\$99 from Mathworks or from journeyed.com, Control System Toolbox \$29

Additional references: Matlab help files, Matlab manual; Student Edition of Matlab
Manual; many, many tutorials on the web; many, many books.

Startup
Win: from the Start button
Mac: you are out of luck, Mathworks discontinued the Mac version

In ITLABS at the University of Minnesota
Windows machines: Start > Programs > MATLAB > MATLAB

Matlab starts up with three windows. Workspace lists variables and functions you have
created or loaded. Command History records your commands. Command Window is
where you enter commands and see answers. If you like, make the Command Window
full screen. Or, View > Desktop Layout > Command Window Only.

>> is the Matlab prompt which will be in the Command Window

Exiting Matlab
>> quit

Help
>> help sin

matlabBasics.doc                       Page 1 of 13                              1/29/2007
Calculator mode
The most basic Matlab mode. Like a super-powerful calculator

>> 2+3

>> 2^3

>> sin(0.5)

>> sin(pi/2)

>> (2+3)*(3+2)

Variables

>> a=25

>> a=25;                    suppresses response

>> a                        getting it back

>> b=5;                     a, b are now in the “workspace”

>> who                      show me what I have in the workspace

>> a/b                      do some calculations

>> c = (a/b)^3              another variable

>> length = 4;              be descriptive

>> width = 3;

>> area = length*width

>> clear                    clears the workspace (watch out)

>> who                      everything is now gone!

>> s = -4 + 2j              complex number (can also use i)

>> abs(s)                   its magnitude

matlabBasics.doc                     Page 2 of 13                  1/29/2007
Pre-named constants
pi, inf, i, j, NAN

Vectors and matrices
This is where Matlab shines! Vectors and matrices are trivial to matrix calculations are
performed with ease.

>> a = [1 2 3 4]              a vector; separate with blanks or commas

>> a = [2 3 4;5 6 7;8 9 0]    a matrix; note row column convention

>> d = a(1,:)                 picks out the first row of the matrix

>> a’                         the transpose

>> det(a)                     just about any matrix function is available
>> inv(a)

>> b = a/2                    vector calculations done element by element

>> a = [1 2;3 4]              multiply matrices
>> b = [5 6;7 8]
>> c = a*b

>> c = [1 2 3 4]              c is a row vector

>> c^2                        an error because you can only square matrices
with equal numbers of rows and columns

>> c.^2                       this gets you element-by-element calculation

>> a = [1 2 3 4 5 …           entering a long row vector taking up two lines
6 7 8]

>> a = [0:0.5:5]              create a long vector

>> a = [0:0.5:2]              and a short one

>> b = sin(a)                 calculating a function at several values

matlabBasics.doc                       Page 3 of 13                             1/29/2007
Functions
You can create and plot a function with Matlab. In the Matlab Help files see entries for
“Representing Functions” and for “flplot”

>> myfunc = inline('2*x^2 + 4*x + 6');            create the function

>> myfunc(2)                    evaluate for x=2

>> fplot('sin', [-2 2]);        plot sin from -2 to 2

>> fplot(myfunc, [-2 2]);       plot my function on same interval
(no apostrophe because inline already a string)

Plots

>> t = [0:0.1:10];              vector of time increments, note the ‘;’

>> y = 5*sin(t);                function of time

>> plot(t,y)                    let’s see what it looks like; y versus t

>> xlabel(‘Time (sec)’)      always label your plots!
>> ylabel(‘Output voltage (v)’)
>> title(‘System response’)

>> plot(t,y), xlabel(‘X’), ylabel(‘y’), title(‘My plot’)    stack commands on one line

>> grid on                      add a grid
>> grid off

>> hold on                      to overly plots on same graph

>> y1 = 3*sin(1.5*t);

>> plot(t,y1);

>> hold off

>> clf                          clear figure

>> plot(t,y,’--')               dash line
>> plot(t,y,’--b')              dash, blue line

>> subplot(2,2,1)               create 2x2 array of small plots, plot to upper left

matlabBasics.doc                         Page 4 of 13                                 1/29/2007
>> plot(t,y)
>> subplot(2,2,2)     plot to upper right
>> plot(t,y1)

>> clf

>> figure(1)          create two separate figures
>> plot(t,y1)
>> figure(2)
>> plot(t,y2)

>> [x,y,z] = peaks;   a nifty 3-d plot demo
>> surf(x,y,z)

matlabBasics.doc              Page 5 of 13          1/29/2007
Custom script and function files (.m files)

Look at the initial condition response of a first-order system

>> t = [0:0.1:10]

>> y = 5*exp(-t/2);            time const = 2
>> plot (t,y)

>> y = 5*exp(-t/1);            time const = 1
>> plot (t,y)

How about a way to just enter the time constant and look at the plot without having to
retype everything each time?

Two ways of doing this: script (or command) files and function files. Script files just run,
function files can take arguments. Script and function files are in plain text format and
have a .m extension on the file name.

Matlab .m files

File > New > M-file

Script file

% tc.m      ‘%’ means a comment line, first line is script name
% To check effect of time constant

t = [0:0.1:10];             % don’t forget the ‘;’
y = 5*exp(-t/tao);
plot(t,y)

Save the file under the name tc.m

To run:

>> tao = 2;                    the time constant
>> tc                          invoke the script just by typing i’s name

>> tao = 1;                    change time constant
>> tc                          invoke the script just by typing i’s name

matlabBasics.doc                       Page 6 of 13                               1/29/2007
Or, do it as a

Function file
function ftc(tao) specifies function name and argument(s)
% To check effect of time constant

t = [0:0.1:10];
y = 5*exp(-t/tao);
plot(t,y)

Save the file under the name ftc.m
To run:

>> ftc(2)                      argument is the time constant
>> ftc(1)

Matlab has a complete programming language that can be used in function and script
files. For example, try this script file which uses a for loop to cycle through a range of
time constants

% manytc.m
% To see the effect of changing the time constant

t = [0:0.1:5];
hold on
for tao=1:5
y = 5*exp(-t/tao);
plot(t,y)
end
hold off

matlabBasics.doc                        Page 7 of 13                               1/29/2007
Simulating systems
Matlab can solve linear and nonlinear differential equations. System equations must be in
state-variable form. So, a second order system with two states must be in this form

dy1/dt = f1(y1, y2, t)

dy2/dt = f2(y1, y2, t)

where y1 and y2 are the states. f1 and f2 are functions of t and incorporate any input
driving the system. You might also have an output equation, if the output is not one of the
state variables

z = g(y1, y2, t)

Matlab simulates this system using a Runge-Kutta algorithm (see any numerical methods
reference). Although Matlab contains several versions of simulators, most problems can
be tackled with the ode45() function.

Simulating a system requires that you write a custom function which contains the state
equations and is called by ode45(). Initial conditions for the states are also fed into
ode45(). The synatx for ode45() is

[t,y] = ode45(‘ydotfunc’, tspan, y0)

where ydotfunc is the name of the custom function, tspan=[t0 tf] (t0 is start time and tf is
end time for the simulation), and y0 is a vector containing the initial conditions of the
states.

A first-order example

The equation: dy/dt + 10*y = 0
In state-variable form: dy/dt = -10*y

Create the custom state equation function as a .m file

function ydot = firstord(t,y)
% First order example

ydot = -10*y;

Save this file as firstord.m

The time constant is 1/10 = 0.1 so let’s look 5 time constants out. This means t0 = 0.0 and
tf = 0.5. Also let the initial condition be 5. The commands to simulate and plot (these
could be placed in a .m script file) are

matlabBasics.doc                        Page 8 of 13                              1/29/2007
>> [t y] = ode45(‘firstord’, [0.0 0.5], 5);
>> plot(t,y), xlabel(‘Time (sec)’), ylabel(‘y(t)’)

How about if we had a forcing function of 10*cos(40*t)?

Now the equation is dy/dt + 10*y = 10*cos(40*t) and in s.v. form,
dy/dt = 10*(-y + cos(40*t))

so in firstord.m, change the line for ydot

ydot = 10*(-y + cos(40*t));

and, just to make it interesting, try an initial condition of y0 = 1.

>> [t y] = ode45(‘firstord’, [0.0 0.5], 1);
>> plot(t,y), xlabel(‘Time (sec)’), ylabel(‘y(t)’)

Type ‘help ode45’ if you get confused

Second order example, the van der Pol equation

The van der Pol equation is a classic example of nonlinear behavior

(d2/dt2)(x) - mu(1-x^2)(d/dt)(x) + x = 0

Choose states y1 and y2. Put the above equation in state variable form

(d/dt)y1 = y2
(d/dt)y2 = mu(1 - y1^2)y2 - y1

Now simulate in Matlab.

First, the custom .m function

function ydot = vdpol(t,y)
% van der pol eqn

mu = 2;
ydot = [y(2); mu*(1-y(1)^2)*y(2) - y(1)];

Note that the state vector y has two elements, y(1) and y(2).
Also note that ydot must be in column vector form
Save this function as vdpol.m.

matlabBasics.doc                         Page 9 of 13                    1/29/2007
Now, run the simulation. We'll create a script function just in case we want to run it
several times

tspan = [0 20];               % time runs from 0 to 20 seconds
y0 = [2; 0];                  % init cond must be a column vector

[t,y] = ode45('vdpol', tspan, y0);

plot(t,y(:,1),t,y(:,2),'--')
xlabel('Time (sec)')
title('van der Pol solution')

Save this under the name nonlin.m

Run the simulation

>> nonlin

Try with different values of mu. To allow you to change mu without having to retype the
function, in the function vdpol.m above, replace the line "mu = 2;" with
"global mu;". The "global" keyword defines the variable as one which can be
modified outside the function, including at the Matlab prompt. At the Matlab prompt, you
must also enter "global mu" before setting mu to a value for the first time. You only have
to do this once. An example is on the next page.

matlabBasics.doc                       Page 10 of 13                              1/29/2007
EXAMPLE SHOWING USE OF GLOBAL VARIABLES TO PASS A
PARAMETER INTO A STATE EQUATION FUNCTION

% runvdpol.m a script file to
% run vdpol showing use of a global variable

tspan = [0 20];    % simulation time
y0 = [2;0];        % initial conditions

global mu
for k = 1:2
mu = k*2;
[t,y] = ode45('vdpol',tspan,y0);
subplot(1,2,k)
plot(t,y(:,1),t,y(:,2),'--')
xlabel('Time (sec)')
title (sprintf('van der Pol, mu = %d',mu))
end

function ydot = vdpol(t,y)
% vdpol.m state equations for vdpol

global mu
ydot = [y(2); mu*(1-y(1)^2)*y(2) - y(1)];

matlabBasics.doc         Page 11 of 13         1/29/2007
Simulink is the block-diagram oriented simulator built on Matlab.

To start Simulink, from the Matlab command prompt:

Simulink has excellent help files. Try
Help > Simulink Help
Then the Getting Started, Quick Start and How Simulink works links

To create a new Simulink model
File > New > Model

If the block library window is not showing then
View > Show Library Browser

Click and drag blocks from browser to workspace.

Location of common blocks:
Where                 Blocks
Continuous            Integrator, Transfer Function
Functions & Tables    MATLAB functions
Math                  Gain, Sum, Trig Function, Math Function
Sinks                 To Workspace, Scope
Sources               Clock, Step, Sine Wave

Name each block by clicking on the name below the block.

To flip a block: Right-Click > Format > Flip Block (or Ctr-I)

To draw a branch line: Use Ctrl key

To view output, use a Scope block

Use To Workspace blocks to bring into Matlab workspace for plotting. The label of the
To Workspace block will be the label of variable in Matlab workspace.

Note: For all To Workspace blocks, double click and set Save Format = Array. Otherwise
your variable will not appear in the Matlab workspace.

Use a Clock block into a To Workspace block to bring time into the workspace. Needed
for plotting variables as a function of time.

To set an initial condition, double click on its associated integrator block.

matlabBasics.doc                       Page 12 of 13                            1/29/2007
Use a Display block (under Sinks) to display the value of a variable. For example can
attach a Display block to the system Clock to monitor simulation time for a particularly
long simulation.

Use From and Goto blocks (under Signals & Systems) to pass signals from one side of a
diagram to the other when long lines would be awkward.

If a Simulink results plot looks choppy, it is because large step sizes were taken in the
auto-step algorithm. To smooth the plot, from the top menu bar select Simulation > The
Max step size parameter determines how large a time step will be used. The smaller the
value the smoother the plot, but the longer the simulation will take. Try entering a value
equal to the simulation time divided by 200 which will guarantee at least 200 points in
the output plots. For example, if the simulation time is 10.0, enter 0.05.

To run Simulink and Matlab together efficiently, see other tutorial document.

matlabBasics.doc                      Page 13 of 13                              1/29/2007

```
DOCUMENT INFO
Shared By:
Categories:
Stats:
 views: 16 posted: 1/19/2010 language: English pages: 13
How are you planning on using Docstoc?