2 - Introduction To MATLAB and Simulink
2 - Introduction To MATLAB and Simulink
MATLAB
High Level
Languages such as
C, Pascal etc
Assembly
Command Window
◦ type commands
Current Directory
◦ View folders and m-files
Workspace
◦ View program variables
◦ Double click on a variable
to see it in the Array Editor
Variable names must start with a letter, may contain only letters,
numbers and the underscore.
Variable names are case sensitive, “time”, “Time”, and “TIME”
are all different variable names.
Variable names can be up to 63 characters long.
Stay away from using MATLAB key words as variable names,
“pi”, “i” or “j”, and MATLAB function names like “sqrt”, “sin”,
“mean”, “max”, etc.
Matrices can be
◦ Row vectors, [ 1, 2, 6, 15, 3, 6]
◦ Rectangular matrices, n rows and m columns
◦ Column vectors, [1; 5; 7; 11]
Matrices can be assigned variable names,
x = [1, 2, 7, 3]
“ ' ” is the complex conjugate transpose operator in MATLAB
At first, working with matrices and formulating problems this
way will seem unnatural, but soon you will catch on and it will
become second nature for you.
+ addition
- subtraction
* multiplication
/ division
^ power
‘ complex conjugate transpose
Note on the previous slide, each line except the last one is
followed by a semi-colon. MATLAB will echo the result of each
line in the Command Window unless you request to suppress it.
Use the semi-colon to suppress the output except for the results
that you specifically want to have output.
int a;
double b;
float c;
a vector x = [1 2 5 1]
x =
1 2 5 1
a matrix x = [1 2 3; 5 1 4; 3 2 -1]
x =
1 2 3
5 1 4
3 2 -1
Transpose y = x’ y =
1
2
5
1
t =1:10
t =
1 2 3 4 5 6 7 8 9 10
k =2:-05:-1
k =
2 15 1 05 0 -05 -1
B = [1:4; 5:8]
x =
1 2 3 4
5 6 7 8
Given:
A(-2), A(0)
Error: ??? Subscript indices must either be real positive integers or logicals
A(4,2)
Error: ??? Index exceeds matrix dimensions
A = [ x y]
1 2 4 5
B = [x ; y]
1 2
4 5
C = [x y ;z]
Error:
??? Error using ==> vertcat CAT arguments dimensions are not consistent
Given A and B:
.* element-by-element multiplication
./ element-by-element division
.^ element-by-element power
A = [1 2 3; 5 1 4; 3 2 1]
A=
1 2 3
5 1 4
3 2 -1
x= y= b= c= d=
1 2 3 3 4 -1 3 8 -3 033 05 -3 1 4 9
K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree
>>x=linspace(0,4*pi,100);
>>plot(y)
plot() 0.7
0.6
0.5
Example: 0.4
>>x=linspace(0,4*pi,100); 0.3
>>y=sin(x); 0.2
>>plot(y)
0.1
>>plot(x,y) -0.1
-0.2
-0.3
0 10 20 30 40 50 60 70 80 90 100
stem() 0.7
0.6
0.5
0.4
0.3
Example:
0.2
0.1
>>stem(y) 0
>>stem(x,y) -0.1
-0.2
-0.3
0 10 20 30 40 50 60 70 80 90 100
area()
Example:
>>x=linspace(0,4*pi,100);
>>y=sin(x);
>>area(x,y)
title()
>>title(‘This is the sinus function’)
xlabel() 1
This is the sinus function
0.8
>>xlabel(‘x (secs)’)
0.6
0.4
0.2
ylabel()
sin(x)
0
-0.2
>>ylabel(‘sin(x)’)
-0.4
-0.6
-0.8
-1
0 10 20 30 40 50 60 70 80 90 100
x (secs)
== Equal to
~= Not equal to
< Strictly smaller
> Strictly greater
<= Smaller than or equal to
>= Greater than equal to
&& And operator
|| Or operator
if
for
while
break
…
If Statement Syntax
Some Dummy Examples
if (Condition_1) if ((a>3) & (b==5))
Matlab Commands Some Matlab Commands;
elseif (Condition_2) end
for m=13:-02:-21
Some Matlab Commands;
end
while (condition)
Matlab Commands Dummy Example
end
while ((a>3) & (b==5))
Some Matlab Commands;
end
Once the file is open with the editor, you can write matlab
commands in it. For instance the three lines:
x=0:0.1:4*pi;
y=sin(x);
plot(x,y);
To execute them, save and name the file then type the name of the
file at the command prompt (you don’t need to type the
extension). For instance:
>>myprogram or >>myprogram.m
This will only work if you have saved your m-file in the ‘working
directory’ – the directory where Matlab first looks to execute
programs.
You can check the working directory in the current directory
frame (shared with Workspace) or by typing >>pwd
Programs can also be executed directly from the editor by
clicking the buttom showing an arrow down next to a page on the
editor toolbar.
Now change the range in the previous script so that it goes up to
6π and re-run the script.
Click to create a
new M-File
• Extension “m”
• A text file containing script or function or program to run
This utility lets you divide a MATLAB program into cells, you
can then execute each cell individually or together with all the
cells.
Use %%_ (_ means space) to identify the beginning of each cell.
Usually following %%_ is the cell name.
Highlight the cell by moving the cursor to the cell.
Click on Cell in the Editor tool bar to select a cell to perform a
function.
Cell Mode is useful when debugging larger programs.
function out1=functionname(in1)
function out1=functionname(in1,in2,in3)
function [out1,out2]=functionname(in1,in2)
You should write this command at the beginning of the m-file and
you should save the m-file with a file name same as the function
name
Precedence Operation
1 Parentheses, innermost first
2 Exponentiation, left to right
3 Multiplication and division, l to r
4 Addition and subtraction, l to r
(a + b)/c + d 5.75
(a + b)/(c+d) 0.333
a + b/(c+d) 1.222
All four expressions are valid and correct depending upon the
problem you are solving.
To avoid confusion when entering long expressions, break them
up into smaller statements and then combine the results. If in
doubt use parentheses to enforce your ordering.
At times you may want to save all or some of the variables and
their values that you’ve created during a session. Later when you
return, you would like to return the Workspace Window to its
previous values and continue your work. To do this you would
use the MATLAB “save” and “load” commands in the Command
Window.
Rather than save all your variables and their values, you can
selectively save and restore by
>> save file_name A B C
◦ to save only the variables A, B, and C.
>> load file_name
will restore the variables and values A, B, and C to the Workspace
Window
numden()
expand()
factor()
collect()
simplify()
simple()
poly2sym()
>> factor(denumerator)
ans =
[x + 3, x + 3]
In the last few years, Simulink has become the most widely used
software package in academia and industry for modeling and
simulating dynamical systems.
Simulink environment encourages you to pose a question, model
it, and see what happens.
You can move beyond idealized linear models to explore more
realistic nonlinear models. Thus, describing real-world
phenomena.
It turns your computer into a lab for modeling and analyzing
systems.
After you define a model, you can simulate it, using a choice of
integration methods, either from the Simulink menus or by
entering commands in MATLAB’s command window.
You can change parameters and immediately see what happens,
for “what if” exploration.
The simulation results can be put in the MATLAB workspace for
postprocessing and visualization
You can create a customized icon and design a dialog box for a
block by using the masking feature.
The model integrates a sine wave and displays the result, along
with the sine wave.
To create this model, you will need to copy blocks into the
model from the following Simulink block libraries:
◦ Sources library (the Sine Wave block)
To copy the Sine Wave block from the Library Browser, first
expand the Library Browser tree to display the blocks in the
Sources library. Do this by clicking first on the Simulink node to
display the Sources node, then on the Sources node to display the
Sources library blocks. Finally click on the Sine Wave node to
select the Sine Wave block.
Now drag the Sine Wave node from the browser and drop it in the
model window.
Now it’s time to connect the blocks. Connect the Sine Wave block
to the top input port of the Mux block. Position the pointer over
the output port on the right side of the Sine Wave block.
First, position the pointer on the line between the Sine Wave and
Second, Press and hold down the Ctrl key. Press the mouse
button, then drag the pointer to the Integrator block’s input port or
On the dialog box that appears, notice that the Stop time is set to
As your model increases in size and complexity, you can simplify
it by grouping blocks into subsystems. Using subsystems has
these advantages:
1. It helps reduce the number of blocks displayed in your model
window.
2. It allows you to keep functionally related blocks together.
3. It enables you to establish a hierarchical block diagram, where a
Subsystem block is on one layer and the blocks that make up the
subsystem are on another.
One of the most confusing issues for new Simulink users is how
to model equations. Here are some examples that may improve
your understanding of how to model equations.
A Sum block, to add the two quantities, also from the Math
library
A Scope block to display the output, from the Sinks library
Next, gather the blocks into your model window.
The Ramp block inputs Celsius temperature. Open that block and
change the Initial output parameter to 0.
The Gain block multiplies that temperature by the constant 9/5.
The Sum block adds the value 32 to the result and outputs the
Fahrenheit temperature.
Open the Scope block to view the output. Now, choose Start from
the Simulation menu to run the simulation. The simulation will
run for 10 seconds.
In this model, to reverse the direction of the Gain block, select the
block, then use the Flip Block command from the Format menu.
Also, to create the branch line from the output of the Integrator
block to the Gain block, hold down the Ctrl key while drawing
the line.
Preparation
𝑑2 𝑥 𝑑𝑥
2
= 5 cos 2𝑡 − 3 − 4𝑥
𝑑𝑡 𝑑𝑡
ssc_dcmotor
Electrical Elements
Electrical Sources
Utilities
Example 1