Difference between revisions of "Simulink/Tutorials/Signals"

From PrattWiki
Jump to navigation Jump to search
Line 45: Line 45:
  
 
==Basic Blocks and Connections==
 
==Basic Blocks and Connections==
The Simulink library is broken up into several categories, and each
+
[[Image:SDDemoSigGen.png|thumb|Figure 1]]
category contains several building blocks for modeling signals and
+
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 <code>Sources</code> 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 <code>Signal Generator</code> block.  Your model should now have a single <code>Signal Generator</code> (fig. 1).  
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 <code>Sources</code> 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 <code>Signal Generator</code> block.  Your
 
model should now have a single <code>Signal Generator</code>.
 
\begin{center}
 
\epsfig{file=./SIMULINK/DemoSigGen.eps}
 
\end{center}
 
  
 
To examine and change the possible parameters of a block, simply
 
To examine and change the possible parameters of a block, simply
Line 65: Line 55:
 
amplitude of the signal, the frequency, and what units of  
 
amplitude of the signal, the frequency, and what units of  
 
frequency to use.  If
 
frequency to use.  If
you were to want to use an input of $x(t)=\sin(8t)$, for example, you would
+
you were to want to use an input of <math>x(t)=\sin(8t)</math>, for example, you would
 
choose a sine wave, using the simulation time, with an amplitude of 1
 
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
 
and a frequency of 8 radians per second.  Go ahead and make those
 
changes, then click the <code>OK</code> button to accept them.
 
changes, then click the <code>OK</code> button to accept them.
  
 +
[[Image:SDDemoGain.png|thumb|Figure 2]]
 
Once you have some kind of input signal, you may want to process it.
 
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
 
There are many different ways to process a signal in Simulink, ranging
Line 78: Line 69:
 
acts like a multiplier.  Drag a copy of this into your model, so that
 
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
 
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.  
+
so it is about an inch to the right of the Signal Generator (fig. 2).  
\begin{center}
 
\epsfig{file=./SIMULINK/DemoGain.eps}
 
\end{center}
 
  
 +
[[Image:SDDemoGain2.png|thumb|Figure 3]]
 
If you double-click
 
If you double-click
 
this block, you will see that it has more options than you may have
 
this block, you will see that it has more options than you may have
Line 88: Line 77:
 
change the Gain itself.  Go ahead and set the gain to 2 and click the
 
change the Gain itself.  Go ahead and set the gain to 2 and click the
 
<code>Apply</code> button.  Notice that the number inside the block itself
 
<code>Apply</code> button.  Notice that the number inside the block itself
changes as a result.   
+
changes as a result (fig. 3).   
\begin{center}
 
\epsfig{file=./SIMULINK/DemoGain2.eps}
 
\end{center}
 
  
 +
[[Image:SDDemoGainK.png|thumb|Figure 4]]
 +
[[Image:SDDemoGainK2.png|thumb|Figure 5]]
 
The number in the gain block will reflect the
 
The number in the gain block will reflect the
 
actual gain if there is room for it - otherwise the gain block will
 
actual gain if there is room for it - otherwise the gain block will
 
have the letter <code>K</code> in it.  For example, if you put in 0.0001 for
 
have the letter <code>K</code> 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.
+
the gain and hit Apply again, the block will just have a K in it (fig. 4).
\begin{center}
 
\epsfig{file=./SIMULINK/DemoGainK.eps}
 
\end{center}
 
 
If you {\it really want} to see the gain, you can change the size of
 
If you {\it 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:
+
the block to make it large enough that the number will fit inside (fig. 5)
\begin{center}
 
\epsfig{file=./SIMULINK/DemoGainK2.eps}
 
\end{center}
 
 
though generally you will not want to resize blocks just to see the
 
though generally you will not want to resize blocks just to see the
 
contents.  The main blocks you will be resizing are those with
 
contents.  The main blocks you will be resizing are those with
Line 112: Line 94:
 
<code>OK</code>, then make the gain block a more normal size.
 
<code>OK</code>, then make the gain block a more normal size.
  
 +
[[Image:SDDemoOuts.png|thumb|Figure 6]]
 
Finally, you will want to have some way of viewing or saving the
 
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
 
data.  If you go back to the original Library window and open up the
Line 120: Line 103:
 
   Workspace</code> to your model.  Put both about an inch to the right of
 
   Workspace</code> to your model.  Put both about an inch to the right of
 
the <code>Gain</code> block, with the <code>Scope} about an inch above and the
 
the <code>Gain</code> block, with the <code>Scope} about an inch above and the
<code>To Workspace} about an inch below.
+
<code>To Workspace} about an inch below (fig. 6).
\begin{center}
 
\epsfig{file=./SIMULINK/DemoOuts.eps}
 
\end{center}
 
  
 
If you double-click the scope, an oscilloscope window will appear.
 
If you double-click the scope, an oscilloscope window will appear.
Line 132: Line 112:
 
   Workspace</code> block comes in.
 
   Workspace</code> block comes in.
  
 +
[[Image:SDDemoOuty.png|thumb|Figure 7]]
 
The <code>To Workspace</code> block will record the signal values sent to  
 
The <code>To Workspace</code> block will record the signal values sent to  
 
it as a variable in
 
it as a variable in
Line 141: Line 122:
 
parameters will generally work fine.  Once done, click <code>OK</code> and
 
parameters will generally work fine.  Once done, click <code>OK</code> and
 
notice that the name of the variable is now showing inside of the
 
notice that the name of the variable is now showing inside of the
block.
+
block (fig. 7).
\begin{center}
 
\epsfig{file=./SIMULINK/DemoOuty.eps}
 
\end{center}
 
  
 +
[[Image:SDDemoWire1.png|thumb|Figure 8]]
 
Now that the blocks are in place, you need to connect them.  You will
 
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
 
notice if you run the cursor over the small port symbol (the $>$) of a
Line 156: Line 135:
 
over the input port of the <code>Gain</code> block.  You will notice that the
 
over the input port of the <code>Gain</code> block.  You will notice that the
 
cursor changes to double crosshairs when you have found a terminus for
 
cursor changes to double crosshairs when you have found a terminus for
your wire.  Now connect the output of the <code>Gain</code> block to the <code>Scope</code>.
+
your wire.  Now connect the output of the <code>Gain</code> block to the <code>Scope</code> (fig. 8).
\begin{center}
 
\epsfig{file=./SIMULINK/DemoWire1.eps}
 
\end{center}
 
  
 
If you also want to connect the <code>Gain</code> block to the <code>To
 
If you also want to connect the <code>Gain</code> block to the <code>To
Line 180: Line 156:
 
(thereby selecting it) and hitting delete.
 
(thereby selecting it) and hitting delete.
  
 +
[[Image:SDDemoWired.png|thumb|Figure 9]]
 
At this point, your model should have all four blocks properly wired,
 
At this point, your model should have all four blocks properly wired,
with a gain of 2 and a <code>To Workspace</code> variable called $y$:
+
with a gain of 2 and a <code>To Workspace</code> variable called $y$ (fig. 9).
\begin{center}
 
\epsfig{file=./SIMULINK/DemoWired.eps}
 
\end{center}
 
 
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.
  
 
+
==Running Simulations==
\section{Running Simulations}
 
 
Now that you have a basic block diagram with an input signal going
 
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
 
through a system that multiplies that signal by 2 as well as two
Line 237: Line 210:
 
and re-plot your results.
 
and re-plot your results.
  
\section{Creating Arbitrary Inputs}
+
==Creating Arbitrary Inputs==
 
There are several ways to create different inputs signals.  The Signal
 
There are several ways to create different inputs signals.  The Signal
 
Generator is certainly the easiest way to create a basic sinusoid,
 
Generator is certainly the easiest way to create a basic sinusoid,
Line 290: Line 263:
 
\end{center}
 
\end{center}
  
\section{Transferring Data}
+
==Transferring Data==
 
As mentioned earlier, you will often want to transfer data from the
 
As mentioned earlier, you will often want to transfer data from the
 
Simulink simulation to the workspace.  The <code>To Workspace</code> block is
 
Simulink simulation to the workspace.  The <code>To Workspace</code> block is
Line 304: Line 277:
 
the times will automatically be captured by the <code>tout</code> vector.
 
the times will automatically be captured by the <code>tout</code> vector.
  
\section{Naming and Arranging Blocks}
+
==Naming and Arranging Blocks==
 
You can change the name of blocks in Simulink by double-clicking the
 
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
 
name you want to change.  This can be very useful if your blocks have
Line 321: Line 294:
 
colors and other options to help clarify your system.
 
colors and other options to help clarify your system.
  
\section{Running Models With Scripts}
+
==Running Models With Scripts==
 
Another way to run a model, besides using the <code>Simulation</code> menu,
 
Another way to run a model, besides using the <code>Simulation</code> menu,
 
is to write a script that interacts with the model.  The advantages of
 
is to write a script that interacts with the model.  The advantages of
Line 437: Line 410:
 
the <code>sim</code> command.
 
the <code>sim</code> command.
  
\section{Saving and Printing Models}
+
==Saving and Printing Models==
 
To save a Simulink model, just go to the File menu and select either
 
To save a Simulink model, just go to the File menu and select either
 
<code>Save</code> or <code>Save As</code>.  Simulink models should end with <code>.mdl</code>.  To print your model, you can either use the Print function
 
<code>Save</code> or <code>Save As</code>.  Simulink models should end with <code>.mdl</code>.  To print your model, you can either use the Print function
Line 465: Line 438:
  
  
\section{Assignment}
 
\subsection{Reading Help Files}
 
As part of the assignment, you need to read
 
several help files in the MATLAB Help Browser.
 
Within the Simulink Library window, go to the Help menu and select </code>Using Simulink</code>.  Read the Getting Started, Simulink Basics,
 
  Creating a Model, Working with Blocks, Working with Signals, Working
 
  with Data, and Modeling with Simulink sections.  Then, again
 
within the Library window, go to the Help menu and select </code>Blocks<code>.  Look at the <code>Blocks - By Category</code> section and read
 
the help files - or at least the one line summaries - for
 
Continuous (Derivative, Integrator, State-space, Transfer Fcn),
 
Discontinuities (Saturation),
 
Discrete (Difference, Discrete Derivative, Discrete State-Space,
 
Discrete Transfer Fcn, Discrete-Time Integrator, Integer Delay, Unit
 
Delay), 
 
Math Operations (All of them),
 
Sinks (All of them),
 
Sources (All of them), and
 
User-Defined Functions (Fcn, MATLAB Fcn).
 
 
 
\subsection{Transfer Functions with Simulink}
 
For this assignment, you will be creating a model of a DC motor in
 
Simulink, then extending it by appliying a controller.  The first
 
block diagram you will replicate is Figure 11.3 on page 443 </code>except<code> do not use a Step block as an input.  Instead, use the
 
arbitrary function block with the clock as described earlier in this
 
manual - that will allow you to investigate how the motor reactions to
 
several kinds of input rather than merely the step response.    Use a
 
value of 1 for the rotational intertia load (called $\E{I}{L}$ here)
 
as well as the rotational damping (called $C$ here).  Use the motor
 
from Problem 10.3 on p. 433 - that is, $\E{K}{t}=0.12$ Nm/A,
 
$\E{K}{e}=12$ V/RPM, and $\E{R}{a}$ = 1.5 $\Omega$.  Note that it
 
would be a good idea to convert the electrical constant into radians
 
per second.  Also note that this particular block diagram has the
 
Laplace transform of the angular {\it speed}, $\Bbb{\Omega}(s)$, as an
 
output - obtaining the angle would require integrating this term -
 
something MATLAB can easily due with an integrator block.
 
 
Once you have the block diagram completed, make a copy of the runner
 
script to take 1 s of data - this should be enough for the motor,
 
given the specific motor constants and load - to reach steady state.
 
Make a plot of the velocity as a function of time (which should
 
somewhat resemble Figure 11.4) and show the TA your graph.
 
 
\subsection{Control}
 
Next, you are going to add a block to represent a controller.  The
 
goal is to set a desired velocity by entering a a specific voltage and
 
then have the system simultaneously measure the desired speed of the
 
device.  The control system will then take the difference between the
 
desired and actual values and manipulate it in accordance with
 
Eqn. 11.9 on p. 444 so that a controlling voltage can be sent to the
 
motor.  Several tasks are accomplished here.  First - with feedback -
 
there is a measuring system that can determine whether the motor is
 
actually doing what it is supposed to and correct it accordingly.
 
Second, any variance caused by external factors can be accommodated.
 
Finally, the speed and general function with which the motor reaches
 
its steady state value can be altered.  In fact, using control a motor
 
that is otherwise stable could potentially be destablized if the wrong
 
kind of control is used!
 
 
Save the Simulink model for just the motor, then <code>Save as...</code>.
 
You will be breaking the connection between the output of the
 
arbitrary function and the input of the summation.  Move the clock and
 
the arbitrary function to the left and then put in the additional
 
blocks (a summation junction and a transfer function) as represented
 
by Figure 11.6 on p. 445.  For now, the PID Controller block should
 
have a transfer function of 1 in it, representing proportional control
 
of magnitude 1.
 
 
 
 
\pagebreak
 
  
\section{Sample Codes and Models}
+
==Sample Codes and Models==
 
\subsection{RunLab2WithScript.m\label{Sim:Runner}}
 
\subsection{RunLab2WithScript.m\label{Sim:Runner}}
 
\listinginput[1]{1}{./SIMULINK/RunLab2Demo2c.m}
 
\listinginput[1]{1}{./SIMULINK/RunLab2Demo2c.m}

Revision as of 16:12, 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.

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

Figure 1

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.

Figure 2

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).

Figure 3

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).

Figure 4
Figure 5

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 {\it 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.

Figure 6

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.
Figure 7

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 {\tt

 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).

Figure 8

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 {\it first} click on the input of the To Workspace then drag until you hit the {\it 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. \pagebreak

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.

Figure 9

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 the Save 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 a
Clock block from the Sources category such that the output of
the Clock 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.  The Fcn block is larger that the Gain block
 so you can only snag one of the wires.  To get the other one, you
 can drag the Fcn 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 either Flip Block or Rotate
 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}