Difference between revisions of "Simulink/Tutorials/Signals"
Line 1: | Line 1: | ||
− | |||
This lab focuses on introducing MATLAB and Simulink and using | This lab focuses on introducing MATLAB and Simulink and using | ||
them to analyze transfer functions and numerically solve | them to analyze transfer functions and numerically solve | ||
differential equations. | differential equations. | ||
Many engineering problems can be easily modeled using block | Many engineering problems can be easily modeled using block | ||
− | diagrams. In the Alciatore and Histand book, block diagrams are used | + | diagrams. |
+ | <!-- EGR 119 specific | ||
+ | In the Alciatore and Histand book, block diagrams are used | ||
as early as Figure 1.3 to graphically illustrate the connection of | as early as Figure 1.3 to graphically illustrate the connection of | ||
transducers, signal processors, and recorders in measurement systems. | transducers, signal processors, and recorders in measurement systems. | ||
Line 10: | Line 11: | ||
of control theory and how a control signal is compared with a measured | of control theory and how a control signal is compared with a measured | ||
output to generate some error signal. | output to generate some error signal. | ||
+ | --> | ||
The creators of MATLAB understand that block diagrams are used to | The creators of MATLAB understand that block diagrams are used to | ||
Line 29: | Line 31: | ||
visualize and save data, control models with a script, and print your model. | 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 | Simulink is an add-on package to MATLAB, and OIT has purchased several | ||
licenses for use on the Linux workstations. To start Simulink, you | licenses for use on the Linux workstations. To start Simulink, you | ||
− | must first start MATLAB (by typing | + | must first start MATLAB (by typing <code>matlab &</code>), then type <code>simulink</code> |
− | + | at the command prompt within MATLAB. At that point, the Simulink library window will come up. | |
− | 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 | 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 | using it to obtain access to the many different built-in blocks that | ||
Simulink provides. | Simulink provides. | ||
− | To start your own model, go to | + | To start your own model, go to <code>File->New->Model</code>. Now you have a blank canvas to work with. To fill it in, you need to |
− | |||
− | To fill it in, you need to | ||
know what the basic blocks are, how to bring them into your model, and | know what the basic blocks are, how to bring them into your model, and | ||
how to connect them. | how to connect them. | ||
− | + | ==Basic Blocks and Connections== | |
The Simulink library is broken up into several categories, and each | The Simulink library is broken up into several categories, and each | ||
category contains several building blocks for modeling signals and | category contains several building blocks for modeling signals and | ||
systems. To look at the contents of a particular category, just | 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 its name in the library window. For example, if you | ||
− | double-click on the | + | double-click on the <code>Sources</code> icon, you will open a new library |
window containing several different ways that MATLAB can generate a | window containing several different ways that MATLAB can generate a | ||
− | signal. | + | 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 | to do is click and hold on it with the left mouse button, then drag it onto | ||
− | your canvas. Try this with the | + | your canvas. Try this with the <code>Signal Generator</code> block. Your |
− | model should now have a single | + | model should now have a single <code>Signal Generator</code>. |
\begin{center} | \begin{center} | ||
\epsfig{file=./SIMULINK/DemoSigGen.eps} | \epsfig{file=./SIMULINK/DemoSigGen.eps} | ||
Line 64: | Line 61: | ||
To examine and change the possible parameters of a block, simply | To examine and change the possible parameters of a block, simply | ||
double-click on it in your model window. | double-click on it in your model window. | ||
− | The | + | The <code>Signal Generator</code>, for example, allows |
you to choose what wave form you would like, the time base to use, the | 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 | amplitude of the signal, the frequency, and what units of | ||
Line 71: | Line 68: | ||
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 | + | changes, then click the <code>OK</code> button to accept them. |
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 | ||
from basic mathematics to advanced image processing and frequency | from basic mathematics to advanced image processing and frequency | ||
− | analysis. For now, open up the | + | analysis. For now, open up the <code>Math Operations</code> category by |
double-clicking it in the original library window. Among the | double-clicking it in the original library window. Among the | ||
− | different operations you can perform is the | + | different operations you can perform is the <code>Gain</code> block, which |
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 | ||
Line 90: | Line 87: | ||
thought for a simple gain. Generally, however, you will only need to | 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 | 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 | |
changes as a result. | changes as a result. | ||
\begin{center} | \begin{center} | ||
Line 98: | Line 95: | ||
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 | + | 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. | ||
\begin{center} | \begin{center} | ||
Line 113: | Line 110: | ||
larger size will make it easier to track and attach 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 | different inputs. In this case, change the gain back to 2 and hit | ||
− | + | <code>OK</code>, then make the gain block a more normal size. | |
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 | ||
− | + | <code>Sinks</code> category, you will see the various ways that MATLAB can | |
take a signal and either send the information to the screen, to the | 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 | workspace, or to a file. In this case, you are going to want to both | ||
− | view and manipulate the data, so drag both a | + | view and manipulate the data, so drag both a <code>Scope</code> and a <code>To |
− | Workspace | + | Workspace</code> to your model. Put both about an inch to the right of |
− | the | + | the <code>Gain</code> block, with the <code>Scope} about an inch above and the |
− | + | <code>To Workspace} about an inch below. | |
\begin{center} | \begin{center} | ||
\epsfig{file=./SIMULINK/DemoOuts.eps} | \epsfig{file=./SIMULINK/DemoOuts.eps} | ||
Line 132: | Line 129: | ||
real time. Generally, you will add these during the construction of a | 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 | model, but once you have completed the model, you will want a more | ||
− | permanent record of the data obtained. This is where the | + | permanent record of the data obtained. This is where the <code>To |
− | Workspace | + | Workspace</code> block comes in. |
− | The | + | The <code>To Workspace</code> block will record the signal values sent to |
it as a variable in | it as a variable in | ||
the MATLAB workspace. If you double-click on the block, you will note | 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 | that you can change the variable name - go ahead and make this {\tt | ||
− | y}. The | + | y}. The <code>Save format</code> that is most readily used is <code>Array</code>, |
so go ahead | so go ahead | ||
and make that change as well. The default cases for the other | and make that change as well. The default cases for the other | ||
− | parameters will generally work fine. Once done, click | + | 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. | ||
Line 154: | Line 151: | ||
you connect blocks is to pick the port of one block, hold down the | 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 | left mouse button, and drag until you hit another port (or another | ||
− | wire). Go ahead and connect the | + | wire). Go ahead and connect the <code>Signal Generator</code> to the <code>Gain</code> block by |
− | + | putting the cursor on top of the output port of the <code>Signal Generator</code>, | |
− | putting the cursor on top of the output port of the | ||
holding down the left mouse button, and dragging until the cursor is | holding down the left mouse button, and dragging until the cursor is | ||
− | over the input port of 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 | + | your wire. Now connect the output of the <code>Gain</code> block to the <code>Scope</code>. |
− | |||
\begin{center} | \begin{center} | ||
\epsfig{file=./SIMULINK/DemoWire1.eps} | \epsfig{file=./SIMULINK/DemoWire1.eps} | ||
\end{center} | \end{center} | ||
− | If you also want to connect the | + | If you also want to connect the <code>Gain</code> block to the <code>To |
− | Workspace | + | Workspace</code> block, |
− | you will need to {\it first} click on the input of the | + | you will need to {\it first} click on the input of the <code>To Workspace</code> |
then drag until you hit the {\it wire} connecting the scope to the | then drag until you hit the {\it wire} connecting the scope to the | ||
− | gain block. You cannot go back to the | + | gain block. You cannot go back to the <code>Gain</code> block's output port, |
because every input or output port can only be used once. | because every input or output port can only be used once. | ||
\pagebreak | \pagebreak | ||
Line 186: | Line 181: | ||
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 | + | with a gain of 2 and a <code>To Workspace</code> variable called $y$: |
\begin{center} | \begin{center} | ||
\epsfig{file=./SIMULINK/DemoWired.eps} | \epsfig{file=./SIMULINK/DemoWired.eps} | ||
\end{center} | \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 | + | double-clicked the <code>Scope</code> block. |
Line 198: | Line 193: | ||
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 | ||
different ways of examining the data, you are ready to simulate the | different ways of examining the data, you are ready to simulate the | ||
− | system. Within the | + | system. Within the <code>Simulation</code> menu of your model, |
− | go to | + | go to <code>Configuration |
− | Parameters | + | Parameters</code> and you will discover that Simulink has an extensive |
array of options from which to choose. For now, the critical part is | array of options from which to choose. For now, the critical part is | ||
telling MATLAB to store all the data and telling MATLAB the | telling MATLAB to store all the data and telling MATLAB the | ||
simulation time. | simulation time. | ||
− | Go to the | + | Go to the <code>Data Import/Export</code> selection and un-check the |
− | Limit data points... | + | <code>Limit data points...</code> option in the <code>Save options</code>. For |
whatever reason, MATLAB defaults on only storing the last thousand | whatever reason, MATLAB defaults on only storing the last thousand | ||
data points unless you specify otherwise. Generally, you will want | data points unless you specify otherwise. Generally, you will want | ||
Simulink to report all the data. | Simulink to report all the data. | ||
− | With respect to timing, go to the | + | With respect to timing, go to the <code>Solver</code> selection. |
The default case - which goes from 0 to | The default case - which goes from 0 to | ||
− | 10 seconds - might work, so go ahead and hit | + | 10 seconds - might work, so go ahead and hit <code>OK</code>. |
− | Then, to run the simulation, go to | + | Then, to run the simulation, go to <code>Simulation</code> and <code>Start</code>. |
The scope will show the values of the output, and when the simulation | The scope will show the values of the output, and when the simulation | ||
is finished, MATLAB will beep. | is finished, MATLAB will beep. | ||
− | If you type | + | If you type <code>whos</code> in MATLAB, you will discover that not only did |
− | you generate an array called | + | you generate an array called <code>y</code> but that Simulink also created an |
− | array called | + | array called <code>tout</code> for you. |
Now you can run the simulation and, when finished, issue the command | Now you can run the simulation and, when finished, issue the command | ||
\begin{verbatim} | \begin{verbatim} | ||
Line 236: | Line 231: | ||
To forestall this, you can go | To forestall this, you can go | ||
− | back into the | + | back into the <code>Simulation</code> menu's <code>Configuration Parameters</code> and make some |
− | changes. Specifically, within the | + | changes. Specifically, within the <code>Solver</code> selection change the |
− | + | <code>Max step size</code> to a reasonable value | |
for the speed of the signal - perhaps 0.01. Re-run the simulation, | for the speed of the signal - perhaps 0.01. Re-run the simulation, | ||
and re-plot your results. | and re-plot your results. | ||
Line 247: | Line 242: | ||
square wave, or sawtooth. For other signals, you can use a | square wave, or sawtooth. For other signals, you can use a | ||
combination of sources and basic math to get what you want. There is | combination of sources and basic math to get what you want. There is | ||
− | even a | + | even a <code>Signal Builder</code> block that can be used to draw signals. |
Generally, however, the easiest way to create an input is to use a | Generally, however, the easiest way to create an input is to use a | ||
− | + | <code>Clock</code> block and feed it into a <code>Fcn</code> block. Go ahead and | |
− | save your current model as | + | save your current model as <code>Lab2Demo1.mdl</code>, then do a ``save as'' |
− | and call it | + | and call it <code>Lab2Demo2.mdl</code>. |
− | Now select and delete both the | + | Now select and delete both the <code>Signal Generator</code> and the |
− | Gain | + | <code>Gain</code> block. Among other changes, you will now be left with |
unconnected lines, denoted by red dotted lines: | unconnected lines, denoted by red dotted lines: | ||
\begin{center} | \begin{center} | ||
Line 262: | Line 257: | ||
can be reused by putting a block's input or output ports close enough | 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 | that Simulink thinks they should be connected. For example, drag a | ||
− | + | <code>Clock</code> block from the Sources category such that the output of | |
− | the | + | the <code>Clock</code> 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 | attach itself to that wire, though the wire will remain red since its | ||
output end is still unconnected. | output end is still unconnected. | ||
− | Now open the | + | Now open the <code>User-Defined Functions</code> category and drag a {\tt |
Fcn} block into your model, placing it in the space vacated by the | Fcn} block into your model, placing it in the space vacated by the | ||
− | gain block. The | + | gain block. The <code>Fcn</code> block is larger that the <code>Gain</code> block |
so you can only snag one of the wires. To get the other one, you | so you can only snag one of the wires. To get the other one, you | ||
− | can drag the | + | can drag the <code>Fcn</code> block again or use the arrow keys to move |
it until it connects and the wire turns solid black. You should now | it until it connects and the wire turns solid black. You should now | ||
have the following model: | have the following model: | ||
Line 278: | Line 273: | ||
\end{center} | \end{center} | ||
− | To enter a function, double-click the | + | To enter a function, double-click the <code>Fcn</code> block. Note that the |
− | expression is currently a function of the vector | + | expression is currently a function of the vector <code>u</code>. This vector |
represents the different inputs to the block. Right now, we are only | represents the different inputs to the block. Right now, we are only | ||
using a single input - though later you can use multiplexers to send | using a single input - though later you can use multiplexers to send | ||
multiple streams along a single line. Your function, therefore, | multiple streams along a single line. Your function, therefore, | ||
− | should be written in terms of | + | should be written in terms of <code>u[1]</code>. For example, if you want |
the output of the function to be $e^{-t/3}\cos(4t)$, then the input to | the output of the function to be $e^{-t/3}\cos(4t)$, then the input to | ||
− | this block should be | + | this block should be <code>exp(-u[1]/3)*cos(4*u[1])</code>. Note - Simulink |
does {\it not} like using the ``.*'' version of multiplication. | does {\it not} like using the ``.*'' version of multiplication. | ||
Once you have that function entered, re-run the simulation. If you | Once you have that function entered, re-run the simulation. If you | ||
− | make a plot of | + | make a plot of <code>y</code> as a function of <code>tout</code> using the command |
− | + | <code>plot(tout, y)</code>, you should get: | |
\begin{center} | \begin{center} | ||
\epsfig{file=./SIMULINK/Lab2DemocPlot.eps, scale=0.4} | \epsfig{file=./SIMULINK/Lab2DemocPlot.eps, scale=0.4} | ||
Line 297: | Line 292: | ||
\section{Transferring Data} | \section{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 | + | Simulink simulation to the workspace. The <code>To Workspace</code> block is |
the easiest way to get a signal's information to the workspace. Just | 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 | make sure that the variable name is unique for each of the blocks and | ||
− | that you have used the | + | that you have used the <code>Array</code> method for storing the data. |
− | There are also | + | There are also <code>From Workspace</code> blocks if you want to pass in |
value and time data from the workspace. Generally for this course, | value and time data from the workspace. Generally for this course, | ||
− | you will be using the clock and the | + | you will be using the clock and the <code>Fcn</code> block to generate your |
input waveforms and will want to make sure that the output from the | input waveforms and will want to make sure that the output from the | ||
− | + | <code>Fcn</code> block is captured in a <code>To Workspace</code> block. Note that | |
− | the times will automatically be captured by the | + | the times will automatically be captured by the <code>tout</code> vector. |
\section{Naming and Arranging Blocks} | \section{Naming and Arranging Blocks} | ||
Line 319: | Line 314: | ||
You may also occasionally want to ``aim'' a block in a different | You may also occasionally want to ``aim'' a block in a different | ||
− | direction - to do this, simply pick the block, then go to the | + | direction - to do this, simply pick the block, then go to the |
− | Format | + | <code>Format</code> menu and select either <code>Flip Block</code> or <code>Rotate |
− | Block | + | Block</code>. You have already seen that you can resize blocks. Take note the |
− | other options in the | + | other options in the <code>Format</code> menu - there may be times with |
particularly sophisticated models that you will want to use various | particularly sophisticated models that you will want to use various | ||
colors and other options to help clarify your system. | colors and other options to help clarify your system. | ||
\section{Running Models With Scripts} | \section{Running Models With Scripts} | ||
− | Another way to run a model, besides using the | + | 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 | ||
using a script include the ability to set all the parameters in a | using a script include the ability to set all the parameters in a | ||
Line 335: | Line 330: | ||
The key commands for using a script to interact with a model are the | The key commands for using a script to interact with a model are the | ||
− | + | <code>get\_param</code> and <code>set\_param</code> functions. The former reports | |
what is currently going on with a system or block while the latter | 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 | allows you to make changes to it. For this demonstration, save the | ||
− | Simulink model with the | + | Simulink model with the <code>Clock</code>, <code>Fcn</code>, <code>Scope</code>, and |
− | + | <code>To Workspace</code> blocks to a file called <code>Lab2WithScript.mdl</code>. | |
Then start a new m file and add | Then start a new m file and add | ||
\begin{lstlisting}[frame=shadowbox] | \begin{lstlisting}[frame=shadowbox] | ||
Line 361: | Line 356: | ||
Now you have an easy way to access a particular file, and if you make | 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 | changes to the model and save it under a new name, you will only need | ||
− | to change the | + | to change the <code>Filename</code> variable to compensate. |
To see all the simulation parameters of the system, add the following | To see all the simulation parameters of the system, add the following | ||
Line 413: | Line 408: | ||
\end{lstlisting} | \end{lstlisting} | ||
and when you run the script, MATLAB will report that the variable name | and when you run the script, MATLAB will report that the variable name | ||
− | is the string | + | is the string <code>y</code>. |
Finally, you may want to make some changes in the code. For example, | 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 | if you want to see how a particular system reacts to several different | ||
− | inputs, you may want to change the function in the | + | inputs, you may want to change the function in the <code>Fcn</code> block. |
To see an example of this, add the following lines of code: | To see an example of this, add the following lines of code: | ||
\begin{lstlisting}[frame=shadowbox] | \begin{lstlisting}[frame=shadowbox] | ||
Line 433: | Line 428: | ||
\end{lstlisting} | \end{lstlisting} | ||
− | The | + | The <code>sim</code> command also has a number of optional arguments that can |
− | be used to reduce the number of | + | be used to reduce the number of <code>set\_param</code> calls required to |
prepare the simulation. These options are generally passed through a | prepare the simulation. These options are generally passed through a | ||
− | function called | + | function called <code>simset</code> which allows you to alter several - |
− | though not all - of the simulation parameters. Type | + | though not all - of the simulation parameters. Type <code>simset</code> in |
the command window to get an idea of the different options that can be | the command window to get an idea of the different options that can be | ||
− | passed through it, and type | + | passed through it, and type <code>help sim</code> for more information about |
− | the | + | the <code>sim</code> command. |
\section{Saving and Printing Models} | \section{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 | |
− | |||
in the File menu or type | in the File menu or type | ||
\begin{verbatim} | \begin{verbatim} | ||
Line 461: | Line 455: | ||
{\tt{\it Filename}model.eps}. If you are going to do several things | {\tt{\it Filename}model.eps}. If you are going to do several things | ||
with the same model, you may | with the same model, you may | ||
− | want to add some kind of flag in the | + | want to add some kind of flag in the <code>sprintf</code> command to |
differentiate among plots. For example, if you are running code in a | differentiate among plots. For example, if you are running code in a | ||
− | loop based on some integer counter | + | loop based on some integer counter <code>k</code>, you could use the |
following code: | following code: | ||
\begin{lstlisting}[frame=single] | \begin{lstlisting}[frame=single] | ||
Line 475: | Line 469: | ||
As part of the assignment, you need to read | As part of the assignment, you need to read | ||
several help files in the MATLAB Help Browser. | several help files in the MATLAB Help Browser. | ||
− | Within the Simulink Library window, go to the Help menu and select | + | 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 | Creating a Model, Working with Blocks, Working with Signals, Working | ||
with Data, and Modeling with Simulink sections. Then, again | with Data, and Modeling with Simulink sections. Then, again | ||
− | within the Library window, go to the Help menu and select | + | 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 | the help files - or at least the one line summaries - for | ||
Continuous (Derivative, Integrator, State-space, Transfer Fcn), | Continuous (Derivative, Integrator, State-space, Transfer Fcn), | ||
Line 496: | Line 488: | ||
For this assignment, you will be creating a model of a DC motor in | For this assignment, you will be creating a model of a DC motor in | ||
Simulink, then extending it by appliying a controller. The first | Simulink, then extending it by appliying a controller. The first | ||
− | block diagram you will replicate is Figure 11.3 on page 443 | + | 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 | manual - that will allow you to investigate how the motor reactions to | ||
several kinds of input rather than merely the step response. Use a | several kinds of input rather than merely the step response. Use a | ||
Line 533: | Line 524: | ||
kind of control is used! | kind of control is used! | ||
− | Save the Simulink model for just the motor, then | + | Save the Simulink model for just the motor, then <code>Save as...</code>. |
You will be breaking the connection between the output of the | You will be breaking the connection between the output of the | ||
arbitrary function and the input of the summation. Move the clock and | arbitrary function and the input of the summation. Move the clock and |
Revision as of 15:50, 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
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
.
\begin{center}
\epsfig{file=./SIMULINK/DemoSigGen.eps}
\end{center}
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.
\begin{center}
\epsfig{file=./SIMULINK/DemoGain.eps}
\end{center}
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.
\begin{center}
\epsfig{file=./SIMULINK/DemoGain2.eps}
\end{center}
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.
\begin{center}
\epsfig{file=./SIMULINK/DemoGainK.eps}
\end{center}
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:
\begin{center}
\epsfig{file=./SIMULINK/DemoGainK2.eps}
\end{center}
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.
\begin{center}
\epsfig{file=./SIMULINK/DemoOuts.eps}
\end{center}
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 {\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.
\begin{center}
\epsfig{file=./SIMULINK/DemoOuty.eps}
\end{center}
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
.
\begin{center}
\epsfig{file=./SIMULINK/DemoWire1.eps}
\end{center}
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.
At this point, your model should have all four blocks properly wired,
with a gain of 2 and a To Workspace
variable called $y$:
\begin{center}
\epsfig{file=./SIMULINK/DemoWired.eps}
\end{center}
There should also be an open Scope window that came about when your
double-clicked the Scope
block.
\section{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.
\section{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}
\section{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.
\section{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.
\section{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.
\section{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
. Read the Getting Started, Simulink Basics,
Using Simulink
\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
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 Blocks. Look at the
Blocks - By Category
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).
except
\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 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
Save as...
.
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}
\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}