Invariably when most people start off using MATLAB or Simulink, they hate it. The main reasons I see for this is people are taught MATLAB very poorly which prevents them from understanding the power of MATLAB and when it should be used.
Before I get into describing how the MATLAB workspace, m
files and Simulink are all related let's first define what each of those is separately and a few of the things you can do with them.
The MATLAB Workspace
The MATLAB workspace contains all of the variables you have created in MATLAB either explicitly via the command window or implicitly through running a .m
file (don't worry I'll come back to these). The simplest method to add a variable to the MATLAB workspace is to directly type into the command window like
>> A = 1
A =
1
which adds the variable A
to the workspace and assigns it a value of 1
. Even simpler though is to simple type 1
like
>> 1
ans =
1
which adds the variable ans
to the workspace with a value of 1
. The default workspace variable for any command executed by MATLAB that is not explicitly assigned to a variable is ans
.
The workspace browser in MATLAB displays information about all of the variables currently in the workspace. For instance if we were to execute, in the command window,
>> A = 5;
>> B = [6 8];
>> C = [3 6 7; 9 11 12];
>> D = eye(max(size(C)));
the workspace browser would look something like
Some Helpful Workspace Commands
The save
and clear
commands are helpful commands that work with the MATLAB workspace. save
lets you save variables from the workspace to a file whilst clear
lets you remove variables from the workspace, thus freeing up memory. clear all
will clear every variable from the workspace.
m
Files
An m-file
(or script file) is a simple text file with a .m
file extension. In it you type MATLAB commands which can be executed sequentially by executing just the m-file
in the command window. For instance, lets copy our commands from above and paste them into an m-file
called mfile_test.m
. Now lets add the command C - A
to the bottom of the m-file
(note do not append a ;
after the command). We can execute this m-file
from the command window and see the output of all of commands within it executed sequentially
>> mfile_test.m
ans =
-2 1 2
4 6 7
m
Files and Functions
m
files can also contain functions. For instance we could write a function that calculates the area and circumference of a circle like
function [A, C] = circle(r)
A = pi*r*r;
C = 2*pi*r;
end
and put it in an m-file
called circle.m
. We could then use this like
>> circle(5)
ans =
78.5398
where ans
now holds the area of a circle with a radius of 5
or
>> [A, C] = circle(5)
A =
78.5398
C =
31.4159
where A
holds the area of the circle and C
the circumference.
Simulink Models
Simulink is a graphical tool that can be used to model various different types of systems as well as modelling dynamic system behaviour. Simulink is closely embedded into the MATLAB ecosystem which adds additional power to it (again I'll come back to this later when describing the similarities).
Simulink models contain blocks which all exhibit different behaviour. There is also the functionality to create your own Simulink blocks should you need. Models in Simulink are made by connecting blocks of different kinds to emulate the system you want to model.
Simulink is quite extensive and I don't recommend learning it on your own. The best way to learn Simulink is invariably as part of a course, Control Systems or Systems Analysis type courses are ideal for this purpose. For that reason I'm not going to dwell on it for much longer here.
How are the MATLAB Workspace, m
Files and Simulink all Related?
Well, the MATLAB workspace is available to both m
files and Simulink. Variables in the MATLAB workspace can be used in both m
files and Simulink.
m
files that contain only scripts (and not functions) will write every variable created in them to the MATLAB workspace. m
files that contain only functions won't write any of the new variables used in those functions to the MATLAB workspace. The only way a function will alter variables in the MATLAB workspace is by assigning an output value to ans
or if you explicitly declare output arguments when calling the function.
Simulink and the MATLAB workspace have a very similar relationship to m
files and the MATLAB workspace. Any variable in the MATLAB workspace is available for use in Simulink (in any part, including configuration). For instance in the below configuration I use the MATLAB workspace variables start_time
, stop_time
and step_time
to set up the parameters of model. Typically I would define these in an m-file
before I run my Simulink model with sim()
. This is how we can relate all 3 together.
Simulink can write variables to the MATLAB workspace by adding output arguments to the sim()
command. However, as you've found this can be quite nasty to navigate and extract what you really want! A better approach would be to use the Data Import/Export options in Simulink coupled with a To Workspace
block to grab the outputs that you are concerned with so that you can ignore everything else.
Below I have a screenshot of the Simulink Data Import/Export pane. You can see there are options in here for us to send variables to the MATLAB workspace. Typically, the most common you would need is tout
which will be a range given by start_time:step_time:stop_time
from the earlier configuration pane. Other areas that would be of primary interest in this screen would be xInitial
and xout
which are used in Root Locus analysis.
However, all that aside one of the best blocks in Simulink is the To Workspace
block. This block can be used to store variables directly in the MATLAB workspace and is one of the keys to being able to link MATLAB and Simulink. You get the power of Simulink but the computational and plotting abilities of MATLAB. I've included a screenshot of it below as well as a typical configuration I would use. The default Save Format
for this block is Timeseries
, however, I recommend changing this to Array
as it will make your life much easier.
OK, where was I? I feel like I'm giving a lecture instead of writing an answer!
A Practical ExplanationSimulink Model
So now let's put everything we've learned into practice with a simple example. First we are going to create a simple Simulink model like this
Now we'll set up our configuration for this, as before for the Solver
section
We'll also untick Limit data points to last:
in the Data Import/Export
section
And, that's it. Our simple Simulink model has been created and setup. For the purposes of this answer, I'm saving mine as stackoverflow_model.slx
.
MATLAB Script
Now we'll create simple MATLAB script (m-file
) called stackoverflow_script.m
that will set up the necessary variables for our Simulink model by adding them to the MATLAB workspace. We'll then call our Simulink model and check what new variables it added to the workspace. And, finally we'll generate a simple plot to show the benefits of this approach.
So here is the MATLAB script
% Script developed to describe the relationship between the MATLAB
% workspace, m-files and Simulink
close all
clear all
% Initialise variables
start_time = 0;
stop_time = 10;
step_time = (stop_time - start_time) / 1000; % Creates 1000 + 1 points
% Choose k
k = 60;
% Execute Simulink model
sim('stackoverflow_model');
whos % To display variables returned from Simulink
% Plot results
figure;
plot(tout, yout, 'r');
title('Sample Plot');
xlabel('Time (s)');
ylabel('Output');
Putting it All Together
Now we execute this script in the command window with stackoverflow_script
and sit back and marvel at the POWER of MATLAB and Simulink combined.
>> stackoverflow_script
Name Size Bytes Class Attributes
k 1x1 8 double
start_time 1x1 8 double
step_time 1x1 8 double
stop_time 1x1 8 double
tout 1001x1 8008 double
yout 1001x1 8008 double
We can see from the output above that all of the variables Simulink needs (k
, start_time
, step_time
and stop_time
) are all in the MATLAB workspace. We can also see that Simulink adds 2 new variables to the MATLAB workspace tout
and yout
which are simple 1001x1
vectors of doubles. No nasty structs
to navigate.
And finally, this produces a nice plot
And so that concludes our whistle stop tour through MATLAB, m
files and Simulink! I hope you've enjoyed it as much as I did writing it!
P.S. I haven't checked this for spelling or grammar mistakes so edits are very much welcome ;)
struct
object and they like verbose trees. A little easier version is to useTo Workspace
block and save only the variables with the optionSignals with Time
then everything would at least be saved under the same container. – percusse