Difference between revisions of "Simulink/Tutorials/Signals"
m |
|||
Line 157: | Line 157: | ||
There should also be an open Scope window that came about when your | There should also be an open Scope window that came about when your | ||
double-clicked the <code>Scope</code> block. | double-clicked the <code>Scope</code> block. | ||
+ | <br clear=all> | ||
==Running Simulations== | ==Running Simulations== |
Revision as of 16:19, 9 April 2009
This lab focuses on introducing MATLAB and Simulink and using them to analyze transfer functions and numerically solve differential equations. Many engineering problems can be easily modeled using block diagrams.
The creators of MATLAB understand that block diagrams are used to visually depict complicated systems, and also that the mathematical characteristics of those systems, once defined, can be used to determine the values for the various signals throughout the system. For that reason, they developed the Simulink package as an add-on to MATLAB. Simulink allows you to draw your system as if you were drawing a block diagram, and then to simulate the system using a variety of computational methods, usually with some component of integration involved.
This introduction will cover starting Simulink, understanding the basic blocks and connections, and running simulations. It will then move on to creating arbitrary functions, transferring data between the model and the workspace, and printing models. By the end of this introduction, you should be able to generate a wide variety of signals, perform basic and intermediate mathematical operations, visualize and save data, control models with a script, and print your model.
Contents
Starting Simulink
Simulink is an add-on package to MATLAB, and OIT has purchased several
licenses for use on the Linux workstations. To start Simulink, you
must first start MATLAB (by typing matlab &
), then type simulink
at the command prompt within MATLAB. At that point, the Simulink library window will come up.
While you will not be creating your model in this window, you will be
using it to obtain access to the many different built-in blocks that
Simulink provides.
To start your own model, go to File->New->Model
. Now you have a blank canvas to work with. To fill it in, you need to
know what the basic blocks are, how to bring them into your model, and
how to connect them.
Basic Blocks and Connections
The Simulink library is broken up into several categories, and each category contains several building blocks for modeling signals and systems. To look at the contents of a particular category, just double-click its name in the library window. For example, if you double-click on the Sources
icon, you will open a new library window containing several different ways that MATLAB can generate a signal. If you want to add one of these to your model, all you have to do is click and hold on it with the left mouse button, then drag it onto your canvas. Try this with the Signal Generator
block. Your model should now have a single Signal Generator
(fig. 1).
To examine and change the possible parameters of a block, simply
double-click on it in your model window.
The Signal Generator
, for example, allows
you to choose what wave form you would like, the time base to use, the
amplitude of the signal, the frequency, and what units of
frequency to use. If
you were to want to use an input of \(x(t)=\sin(8t)\), for example, you would
choose a sine wave, using the simulation time, with an amplitude of 1
and a frequency of 8 radians per second. Go ahead and make those
changes, then click the OK
button to accept them.
Once you have some kind of input signal, you may want to process it.
There are many different ways to process a signal in Simulink, ranging
from basic mathematics to advanced image processing and frequency
analysis. For now, open up the Math Operations
category by
double-clicking it in the original library window. Among the
different operations you can perform is the Gain
block, which
acts like a multiplier. Drag a copy of this into your model, so that
now you have a Signal Generator and a Gain block. Move the Gain block
so it is about an inch to the right of the Signal Generator (fig. 2).
If you double-click
this block, you will see that it has more options than you may have
thought for a simple gain. Generally, however, you will only need to
change the Gain itself. Go ahead and set the gain to 2 and click the
Apply
button. Notice that the number inside the block itself
changes as a result (fig. 3).
The number in the gain block will reflect the
actual gain if there is room for it - otherwise the gain block will
have the letter K
in it. For example, if you put in 0.0001 for
the gain and hit Apply again, the block will just have a K in it (fig. 4).
If you really want to see the gain, you can change the size of
the block to make it large enough that the number will fit inside (fig. 5)
though generally you will not want to resize blocks just to see the
contents. The main blocks you will be resizing are those with
multiple inputs or outputs, for example, summation blocks there the
larger size will make it easier to track and attach the
different inputs. In this case, change the gain back to 2 and hit
OK
, then make the gain block a more normal size.
Finally, you will want to have some way of viewing or saving the
data. If you go back to the original Library window and open up the
Sinks
category, you will see the various ways that MATLAB can
take a signal and either send the information to the screen, to the
workspace, or to a file. In this case, you are going to want to both
view and manipulate the data, so drag both a Scope
and a To Workspace
to your model. Put both about an inch to the right of
the Gain
block, with the Scope
about an inch above and the
To Workspace
about an inch below (fig. 6).
If you double-click the scope, an oscilloscope window will appear.
The scope is useful for viewing the signals throughout a simulation in
real time. Generally, you will add these during the construction of a
model, but once you have completed the model, you will want a more
permanent record of the data obtained. This is where the To Workspace
block comes in.
The To Workspace
block will record the signal values sent to
it as a variable in
the MATLAB workspace. If you double-click on the block, you will note
that you can change the variable name - go ahead and make this y
. The Save format
that is most readily used is Array
,
so go ahead
and make that change as well. The default cases for the other
parameters will generally work fine. Once done, click OK
and
notice that the name of the variable is now showing inside of the
block (fig. 7).
Now that the blocks are in place, you need to connect them. You will
notice if you run the cursor over the small port symbol (the \(>\)) of a
block that the cursor changes from an arrow to crosshairs. The way
you connect blocks is to pick the port of one block, hold down the
left mouse button, and drag until you hit another port (or another
wire). Go ahead and connect the Signal Generator
to the Gain
block by
putting the cursor on top of the output port of the Signal Generator
,
holding down the left mouse button, and dragging until the cursor is
over the input port of the Gain
block. You will notice that the
cursor changes to double crosshairs when you have found a terminus for
your wire. Now connect the output of the Gain
block to the Scope
(fig. 8).
If you also want to connect the Gain
block to the
To Workspace
block,
you will need to first click on the input of the To Workspace
then drag until you hit the wire connecting the scope to the
gain block. You cannot go back to the Gain
block's output port,
because every input or output port can only be used once.
Since every wire should have at least one new port connection, you must begin from that port. Again, you will get the double crosshairs when you are over a wire such that a connection will be made and you will notice a node symbol (small black dot) at the connection. If you make a mistake and drop the wire before it is connected, you will get a dashed red wire with a port symbol at the end of it. You can remove this wire by left clicking on it (thereby selecting it) and hitting delete.
At this point, your model should have all four blocks properly wired,
with a gain of 2 and a To Workspace
variable called \(y\) (fig. 9).
There should also be an open Scope window that came about when your
double-clicked the Scope
block.
Running Simulations
Now that you have a basic block diagram with an input signal going
through a system that multiplies that signal by 2 as well as two
different ways of examining the data, you are ready to simulate the
system. Within the Simulation
menu of your model,
go to Configuration
Parameters
and you will discover that Simulink has an extensive
array of options from which to choose. For now, the critical part is telling MATLAB to store all the data and telling MATLAB the simulation time.
Go to the Data Import/Export
selection and un-check the
Limit data points...
option in theSave options
. For whatever reason, MATLAB defaults on only storing the last thousand data points unless you specify otherwise. Generally, you will want Simulink to report all the data.
With respect to timing, go to the Solver
selection.
The default case - which goes from 0 to
10 seconds - might work, so go ahead and hit OK
.
Then, to run the simulation, go to Simulation
and Start
.
The scope will show the values of the output, and when the simulation
is finished, MATLAB will beep.
If you type whos
in MATLAB, you will discover that not only did
you generate an array called y
but that Simulink also created an
array called tout
for you.
Now you can run the simulation and, when finished, issue the command
\begin{verbatim}
plot(tout, y)
\end{verbatim}
in MATLAB's command window
to plot the signal. When you do this, you will notice something very
disturbing - the output signal does not look like a sine wave a 8
radians per second. This is because Simulink, while processing your
model, tries to solve as quickly as possible by taking as large a time
step as possible. For this particular model, allowing it to do that
has produces a somewhat disastrous result - the locations at which data
points were taken, if connected using lines, do not accurately
represent the signal.
To forestall this, you can go
back into the Simulation
menu's Configuration Parameters
and make some
changes. Specifically, within the Solver
selection change the
Max step size
to a reasonable value
for the speed of the signal - perhaps 0.01. Re-run the simulation,
and re-plot your results.
Creating Arbitrary Inputs
There are several ways to create different inputs signals. The Signal
Generator is certainly the easiest way to create a basic sinusoid,
square wave, or sawtooth. For other signals, you can use a
combination of sources and basic math to get what you want. There is
even a Signal Builder
block that can be used to draw signals.
Generally, however, the easiest way to create an input is to use a
Clock
block and feed it into a Fcn
block. Go ahead and
save your current model as Lab2Demo1.mdl
, then do a ``save as
and call it Lab2Demo2.mdl
.
Now select and delete both the Signal Generator
and the
Gain
block. Among other changes, you will now be left with
unconnected lines, denoted by red dotted lines:
\begin{center} \epsfig{file=./SIMULINK/Lab2Demo2uc.eps} \end{center}
These can be deleted by selecting them and hitting delete, or they can be reused by putting a block's input or output ports close enough that Simulink thinks they should be connected. For example, drag aClock
block from the Sources category such that the output of theClock
is near the left-most part of the left line. It will attach itself to that wire, though the wire will remain red since its output end is still unconnected.
Now open the User-Defined Functions
category and drag a {\tt
Fcn} block into your model, placing it in the space vacated by the gain block. TheFcn
block is larger that theGain
block so you can only snag one of the wires. To get the other one, you can drag theFcn
block again or use the arrow keys to move it until it connects and the wire turns solid black. You should now have the following model:
\begin{center} \epsfig{file=./SIMULINK/Lab2Demo2c.eps} \end{center}
To enter a function, double-click the Fcn
block. Note that the
expression is currently a function of the vector u
. This vector
represents the different inputs to the block. Right now, we are only
using a single input - though later you can use multiplexers to send
multiple streams along a single line. Your function, therefore,
should be written in terms of u[1]
. For example, if you want
the output of the function to be $e^{-t/3}\cos(4t)$, then the input to
this block should be exp(-u[1]/3)*cos(4*u[1])
. Note - Simulink
does {\it not} like using the ``.* version of multiplication.
Once you have that function entered, re-run the simulation. If you
make a plot of y
as a function of tout
using the command
plot(tout, y)
, you should get:
\begin{center}
\epsfig{file=./SIMULINK/Lab2DemocPlot.eps, scale=0.4}
\end{center}
Transferring Data
As mentioned earlier, you will often want to transfer data from the
Simulink simulation to the workspace. The To Workspace
block is
the easiest way to get a signal's information to the workspace. Just
make sure that the variable name is unique for each of the blocks and
that you have used the Array
method for storing the data.
There are also From Workspace
blocks if you want to pass in
value and time data from the workspace. Generally for this course,
you will be using the clock and the Fcn
block to generate your
input waveforms and will want to make sure that the output from the
Fcn
block is captured in a To Workspace
block. Note that
the times will automatically be captured by the tout
vector.
Naming and Arranging Blocks
You can change the name of blocks in Simulink by double-clicking the name you want to change. This can be very useful if your blocks have real-world analogs. You can also probably come up with much more interesting names than ``To Workspace for your outputs. Avoid using dots or slashes in the block names, however. Stick with letters and numbers if at all possible. This will become more important in the next section.
You may also occasionally want to ``aim a block in a different direction - to do this, simply pick the block, then go to the
Format
menu and select eitherFlip Block
orRotate Block
. You have already seen that you can resize blocks. Take note the
other options in the Format
menu - there may be times with
particularly sophisticated models that you will want to use various
colors and other options to help clarify your system.
Running Models With Scripts
Another way to run a model, besides using the Simulation
menu,
is to write a script that interacts with the model. The advantages of
using a script include the ability to set all the parameters in a
single file without navigating menus, the ability to change parameters
of a model in a loop to perform multiple runs consecutively, and the
ability to edit the script later to make several changes to the model.
The key commands for using a script to interact with a model are the
get\_param
and set\_param
functions. The former reports
what is currently going on with a system or block while the latter
allows you to make changes to it. For this demonstration, save the
Simulink model with the Clock
, Fcn
, Scope
, and
To Workspace
blocks to a file called Lab2WithScript.mdl
.
Then start a new m file and add
\begin{lstlisting}[frame=shadowbox]
% Startup
clear
format short e
\end{lstlisting}
to it. This will make sure the workspace is clear before moving
forward and that number will be presented using scientific notation
with five significant figures. Save this file as {\tt
RunLab2WithScript.m}. The completed file is given in Section
\ref{Sim:Runner} on page \pageref{Sim:Runner}.
To work with a system, you will need to refer to the system by name
and make sure it is open, so add the lines:
\begin{lstlisting}[frame=shadowbox]
% Define filename
Filename = 'Lab2WithScript'
open_system(Filename)
\end{lstlisting}
Now you have an easy way to access a particular file, and if you make
changes to the model and save it under a new name, you will only need
to change the Filename
variable to compensate.
To see all the simulation parameters of the system, add the following to your script: \begin{lstlisting}[frame=shadowbox] % Get info about the simulation get_param(Filename, 'ObjectParameters') \end{lstlisting} This command will print out the names of all the different parameters you can set for the simulation. As you can plainly see, there are many, many different options when running simulations. To set some of the most common, you can add the following to your code: \begin{lstlisting}[frame=shadowbox] % Set typical simulation parameters %% Solver %%% Simulation time set_param(Filename, 'StartTime', '0') set_param(Filename, 'StopTime', '10') %%% Solver options set_param(Filename, 'Solver', 'ode45') set_param(Filename, 'MaxStep', 'auto') set_param(Filename, 'MinStep', 'auto') set_param(Filename, 'InitialStep', 'auto') set_param(Filename, 'RelTol', '1e-3') set_param(Filename, 'AbsTol', 'auto') %% Data Import/Export %%% Save options set_param(Filename, 'LimitDataPoints', 'off') \end{lstlisting} Note that the comments with two percent signs refer to the category within the configuration parameters and the comments with three percent signs indicate subsections of those pages. The comments are meant to match the way information is presented in the graphical menu for {\tt
Configuration Parameters}.
Next, you may want to examine the blocks. Add the following lines of
code:
\begin{lstlisting}[frame=shadowbox]
% Get info about the blocks
get_param([Filename '/Clock'], 'ObjectParameters')
get_param([Filename '/Fcn'], 'ObjectParameters')
get_param([Filename '/Scope'], 'ObjectParameters')
get_param([Filename '/To Workspace'], 'ObjectParameters')
\end{lstlisting}
and you will be able to see all the options that accompany each
block. If you want to know what is in a specific parameter, put that
parameter's name in the second argument. Add the following line of
code:
\begin{lstlisting}[frame=shadowbox]
get_param([Filename '/To Workspace'], 'VariableName')
\end{lstlisting}
and when you run the script, MATLAB will report that the variable name
is the string y
.
Finally, you may want to make some changes in the code. For example,
if you want to see how a particular system reacts to several different
inputs, you may want to change the function in the Fcn
block.
To see an example of this, add the following lines of code:
\begin{lstlisting}[frame=shadowbox]
% Set function block info
set_param([Filename '/Fcn'], 'Expression', 'cos(u[1])')
\end{lstlisting}
To run the script and plot the data, use can use the code: \begin{lstlisting}[frame=shadowbox] % Run the system sim(Filename) % Plot the data plot(tout, y, 'ko:') \end{lstlisting}
The sim
command also has a number of optional arguments that can
be used to reduce the number of set\_param
calls required to
prepare the simulation. These options are generally passed through a
function called simset
which allows you to alter several -
though not all - of the simulation parameters. Type simset
in
the command window to get an idea of the different options that can be
passed through it, and type help sim
for more information about
the sim
command.
Saving and Printing Models
To save a Simulink model, just go to the File menu and select either
Save
or Save As
. Simulink models should end with .mdl
. To print your model, you can either use the Print function
in the File menu or type
\begin{verbatim}
print -deps -sMODELNAME FILENAME.eps
\end{verbatim}
The following code will not only print the model based on the
filename, it will also save and close the model window when the script
is finished:
\begin{lstlisting}[frame=single]
eval(sprintf('print -s%s -deps %smodel', Filename, Filename))
save_system(Filename)
close_system(Filename)
\end{lstlisting}
The name of the saved picture of the model will be
{\tt{\it Filename}model.eps}. If you are going to do several things
with the same model, you may
want to add some kind of flag in the sprintf
command to
differentiate among plots. For example, if you are running code in a
loop based on some integer counter k
, you could use the
following code:
\begin{lstlisting}[frame=single]
eval(sprintf('print -s%s -deps %smodel_%0.0f', Filename, Filename, k))
\end{lstlisting}
\pagebreak
Sample Codes and Models
\subsection{RunLab2WithScript.m\label{Sim:Runner}} \listinginput[1]{1}{./SIMULINK/RunLab2Demo2c.m}
\subsection{Lab2WithScript.mdl\label{Sim:L2WS}} \begin{center} \epsfig{file=./SIMULINK/Lab2WithScriptmodel.eps} \end{center}
\subsection{Generic First Derivative Model: FirstDeriv.mdl} \begin{center} \epsfig{file=./SIMULINK/FirstDerivmodel.eps, angle=-90, scale=0.8} \end{center}
\subsection{Generic Second Derivative Model: SecondDeriv.mdl} \begin{center} \epsfig{file=./SIMULINK/SecondDerivmodel.eps, angle=-90, scale=0.8} \end{center} \pagebreak
\subsection{Generic First Derivative Script: RunFD.m} \listinginput[1]{1}{./SIMULINK/RunFD.m} \pagebreak
\subsection{Generic Second Derivative Script: RunSD.m} \listinginput[1]{1}{./SIMULINK/RunSD.m} \pagebreak
\subsection{gzoom.m} \listinginput[1]{1}{./SIMULINK/gzoom.m}