Introduction To Matlab and Simulink
Introduction To Matlab and Simulink
Total Marks
You type all your commands after the command Prompt “>>”, e.g., defining the following
matrix:
A= [ 10 32]
The MATLAB syntax is as follows:
>> A = [1 2; 0 3]
Or
>> A = [1, 2; 0, 3]
Workspace
The Workspace window list all your variables used as long you have MATLAB opened.
Basic Operations
Variables:
Variables are defined with the assignment operator, “=”. MATLAB is dynamically typed,
meaning that variables can be assigned without declaring their type, and that their type can
change. Values can come from constants, from computation involving values of other
variables, or from the output of a function.
>> x = 17
x =
17
>> x = 'hat'
x =
hat
Unlike many other languages, where the semicolon is used to terminate commands, in
MATLAB the semicolon serves to suppress the output of the line that it concludes.
>> a=5
a =
5
Built-in constants:
MATLAB have several built-in constants. Some of them are explained here:
Name Description
i, j Used for complex numbers, e.g.,
z=2+4i
pi 𝜋
inf ∞, Infinity
Built-in Functions:
Here are some descriptions for the most used basic built-in MATLAB functions.
Function Description Example
help MATLAB displays the >>help
help information
available
help<function> Display help about a >>help plot
specific function
who, whos who lists in alphabetical >>who
order all variables in the >>whos
currently
active workspace.
clear all;
close all;
% Generate a random vector with 100 random numbers between 0 and 100
random_vector = rand(1,100)*100;
min_value = min(random_vector);
max_value = max(random_vector);
mean_value = mean(random_vector);
A=
[ 13 24 ]
>> A = [1 2; 3 4]
A = 1 2
3 4
Or:
>> A = [1, 2; 3, 4]
A = 1 2
3 4
→ To separate rows, we use a semicolon “;”
→ To separate columns, we use a comma “,” or a space “ “.
To get a specific part of a matrix, we can type like this:
>>A(2,1)
ans =
3
or:
>>A(:,1)
ans =
1
3
or:
>>A(2,:)
ans =
3 4
From 2 vectors x and y we can create a matrix like this:
>> x = [1; 2; 3];
>> y = [4; 5; 6];
>> B = [x y]
B =
1 4
2 5
3 6
Colon Notation
This example shows how to use the colon notation creating a vector and do some
calculations.
[]
1
x= 2
3
A=
[ 0 1
−2 −3 ]
Type the following matrix in the Command window:
[ ]
−1 2 0
B= 4 10 −2
1 0 6
→ Use MATLAB to find the value in the second row and the third column of matrix B.
→ Use MATLAB to find the second row of matrix B
→ Use MATLAB to find the third column of matrix B.
Write the code in the Box
clc;
close all;
clear all;
x = [1; 2; 3];
A = [0 1; -2 -3];
B = [-1 2 0; 4 10 2; 1 0 6];
% Find the value in the second row and the third column of matrix B
B(2, 3)
B(2, :)
B(:, 3)
A=
[−20 −31 ]
To delete the second column of a matrix 𝐴, use:
>>A= [0 1; -2 -3];
>>A (:,2) = []
A =
0
-2
Array Operations
We have the following basic matrix operations:
>> A = [1; 2; 3]
A =
1
2
3
B =
-6
7
10
>> A*B
??? Error using ==>mtimes
Inner matrix dimensions must agree.
>> A.*B
ans =
-6
14
30
Linear Algebra; Vectors and Matrices
Linear Algebra is a branch of mathematics concerned with the study of matrices, vectors,
vector spaces (also called linear spaces), linear maps (also called linear transformations),
and systems of linear equations.
Here are some useful functions for Linear Algebra in MATLAB:
Function Description Example
rank Find the rank of a >>A=[1 2; 3 4]
matrix. Provides an >>rank(A)
estimate of the number
of linearly independent
rows or columns of a
matrix A.
Matrices
Given a matrix 𝐴:
[
A= 0 1
−2 −3 ]
>> A=[0 1;-2 -3]
A =
0 1
-2 -3
ans =
0 -2
1 -3
The Diagonal elements of matrix A is the vector:
>>diag (A)
ans =
0
-3
For 3x3 identity matrix:
>>eye(3)
ans =
1 0 0
0 1 0
0 0 1
Matrix Multiplication
Multiplication
>> A = [0 1;-2 -3]
A =
0 1
-2 -3
>> B = [1 0; 3 -2]
B =
1 0
3 -2
>> A*B
ans =
3 -2
-11 6
Check the answer by manually calculating using pen & paper.
Addition
>> A = [0 1;-2 -3]
>> B = [1 0;3 -2]
>> A + B
ans =
1 1
1 -5
Determinant
The Determinant of matrix A is given by
det ( A)=|A|
A =
0 1
-2 -3
>>det (A)
ans =
2
Check the answer by manually calculating using pen & paper.
>>det(A*B)
ans =
-4
>>det(A)*det(B)
ans =
-4
>>det(A')
ans =
2
>>det(A)
ans =
Inverse Matrices
The inverse of a quadratic matrix 𝐴 is defined by:
−1
A
For a 2𝑥2 matrix we have:
A=
[ a11 a12
a 21 a23 ]
The inverse A−1 is then given by
−1
A =
[
1 a11 a 12
det A a21 a 23 ]
A =
0 1
-2 -3
>>inv(A)
ans =
-1.5000 -0.5000
1.0000 0
Check the answer by manually calculating using pen & paper.
Eigenvalues
Given Matrix 𝐴∈𝑅, then the Eigenvalues is defined as:
det ( λI – A)=0
A =
0 1
-2 -3
>>eig(A)
ans =
-1
-2
Task 4: Matrix manipulation
Given the matrices 𝐴, 𝐵 and 𝐶:
0 1 1 0 1 −1
A=⌈ ⌉ B=⌈ ⌉ C=⌈ ⌉
−2 −3 3 −2 2 −2
Solve the following basic matrix operations using MATLAB:
A+ B
A−B
T
A
−1
A
diagA , diag( B)
detA , det (B)
detAB
eigA
B = [1, 0; 3, -2];
% Find A + B
A_plus_B = A + B
B = [1, 0; 3, -2];
% Find A - B
A_minus_B = A – B
A
T %ABDUL MOIZ BASHIR-22961%
B = [1, 0; 3, -2];
% Find A^T
A_transpose = A'
B = [1, 0; 3, -2];
% Find diag(A)
diag_A = diag(A)
% Find diag(B)
diag_B = diag(B)
A
−1 %ABDUL MOIZ BASHIR-22961%
B = [1, 0; 3, -2];
% Find A^-1
A_inverse = inv(A)
B = [1, 0; 3, -2];
% Find det(A)
det_A = det(A)
% Find det(B)
det_B = det(B)
% Define the matrices A, B, and C
B = [1, 0; 3, -2];
% Find det(AB)
det_AB = det(A*B)
B = [1, 0; 3, -2];
% Find eig(A)
eig_A = eig(A)
MATLAB can easily be used to solve a large amount of linear equations using built-in
functions.
close all;
clear all;
% Define A and b
A = [1, 2; 3, 4];
b = [5; 6];
A_inv = inv(A);
% Solve for x
x = A_inv*b
When dealing with large matrices (finding inverse of A is time-consuming) or the inverse
doesn’t exist other methods are used to find the solution, such as:
LU factorization
Singular value Decomposition
Etc.
In MATLAB we can also simply use the backslash operator “\” in order to find the solution
like this:
≫x = A\b
Example:
Given the following equations:
x 1+2 x 2=5
3 x 1+ 4 x 2=6
7 x 1+8 x 2=9
From the equations we find:
[ ]
1 2
A= 3 4
7 8
[]
5
b= 6
7
As you can see, the 𝐴 matrix is not a quadratic matrix, meaning we cannot find the inverse
of 𝐴, thus x= A−1 b will not work (try it in MATLAB and see what happens).
So we can solve it using the backslash operator “\”:
A = [1 2; 3 4; 7 8];
b = [5; 6; 9];
x = A\b
Actually, when using the backslash operator “\” in MATLAB it uses the LU factorization
as
part of the algorithm to find the solution.
Plotting
Plotting is a very important and powerful feature in MATLAB. In this Session we will
learn
The basic plotting functionality in MATLAB.
Plots functions: Here are some useful functions for creating plots:
Function Description Example Plot(Paste each plot with change
here)
Type “help graphics” in the Command Window for more information, or type “help
<functionname>” for help about a specific function.
Here we see some examples of how to use the different plot functions:
Task 6: Plotting
In the Command window in MATLAB window input the time from 𝑡 = 0 seconds to 𝑡 = 10
Seconds in increments of 0.1 seconds as follows:
>>t = [0:0.1:10];
Then, compute the output y as follows:
>>y = cos (t);
Use the Plot command:
>>plot(t,y)
Paste the plot result in the box
SIMULINK
Simulink provides access to an extensive set of blocks that accomplish a wide range of
functions useful for the simulation and analysis of dynamic systems. The blocks are grouped
into libraries, by general classes of functions.
Mathematical functions such as summers and gains are in the Math library.
Integrators are in the Continuous library.
Constants, common input functions, and clock can all be found in the Sources library.
Scope, To Workspace blocks can be found in the Sinks library.
Simulink is a graphical interface that allows the user to create programs that are actually run
in MATLAB. When these programs run, they create arrays of the variables defined in
Simulink that can be made available to MATLAB for analysis and/or plotting. The variables
to be used in MATLAB must be identified by Simulink using a “To Workspace” block,
which is found in the Sinks library. (When using this block, open its dialog box and specify
that the save format should be Matrix, rather than the default, which is called Structure.) The
Sinks library also contains a Scope, which allows variables to be displayed as the simulated
system responds to an input. This is most useful when studying responses to repetitive inputs.
Simulink uses blocks to write a program. Blocks are arranged in various libraries according
to their functions. Properties of the blocks and the values can be changed in the associated
dialog boxes. Some of the blocks are given below.
SUM (Math library)
A dialog box obtained by double-clicking on the SUM block performs the configuration of
the SUM block, allowing any number of inputs and the sign of each. The sum block can be
represented in two ways in Simulink, by a circle or by a rectangle. Both choices are shown
which performs a similar function with electronic signals. Any of the variables in a Simulink
diagram can be connected to the Scope block, and when the simulation is started, that
variable is displayed. It is possible to include several Scope blocks. Also it is possible to
display several signals in the same scope block using a MTJX block in the signals & systems
library. The Scope normally chooses its scales automatically to best display the data.
CLOCK (Sources library)
The clock produces the variable “time” that is associated with the integrators as MATLAB
calculates a numerical (digital) solution to a model of a continuous system. The result is a
string of sample values of each of the output variables. These samples are not necessarily at
uniform time increments, so it is necessary to have the variable “time” that contains the time
corresponding to each sample point. Then MATLAB can make plots versus “time.” The
clock output could be given any arbitrary name; we use “t” in most of the cases.
To Workspace (Sinks library)
The To Workspace block is used to return the results of a simulation to the MATLAB
workspace, where they can be analyzed and/or plotted. Any variable in a Simulink diagram
can be connected to a ToWorkspace block. In our exercises, all of the state variables and the
input variables are usually returned to the workspace. In addition, the result of any output
equation that may be simulated would usually be sent to the workspace. In the block
parameters drop down window, change the save format to ‘array’.
In the Simulink diagram, the appearance of a block can be changed by changing the
foreground or background colours, or by drop shadow or other options available in the format
drop down menu. The available options can be reached in the Simulink window by
highlighting the block, then clicking the right mouse button. The Show Drop Shadow option
is on the format drop-down menu.
Simulink provides scores of other blocks with different functions.
You are encouraged to browse the Simulink libraries and consult the online Help facility
provided with MATLAB.
GENERAL INSTRUCTIONS FOR WRITING A SIMULINK PROGRAM
To create a simulation in Simulink, follow the steps:
Start MATLAB.
Start Simulink
Open the libraries that contain the blocks you will need. These usually will include
the Sources, Sinks, Math and Continuous libraries, and possibly others.
Open a new Simulink window.
Drag the needed blocks from their library folders to that window. The Math library,
for example, contains the Gain and Sum blocks.
Arrange these blocks in an orderly way corresponding to the equations to be solved.
Interconnect the blocks by dragging the cursor from the output of one block to the
input of another block. Interconnecting branches can be made by right-clicking on an
existing branch.
Double-click on any block having parameters that must be established and set these
parameters. For example, the gain of all Gain blocks must be set. The number and
signs of the inputs to a Sum block must be established. The parameters of any source
blocks should also be set in this way.
It is necessary to specify a stop time for the solution. This is done by clicking on the
Simulation > Parameters entry on the Simulink toolbar.
At the Simulation > Parameters entry, several parameters can be selected in this dialog box,
but the default values of all of them should be adequate for almost all of the exercises. If the
response before time zero is needed, it can be obtained by setting the Start time to a negative
value. It may be necessary in some problems to reduce the maximum integration step size
used by the numerical algorithm. If the plots of the results of a simulation appear “choppy” or
composed of straight-line segments when they should be smooth, reducing the max step size
permitted can solve this problem.
Lab Task:
Create model in Simulink for the equations given below:
Function Simulink Model
1. Y=2x
2. Y=2x+1
3. dy/
dx=2x+1
4. y=2x+y
Conclusion:
MATLAB is a powerful tool for designing and analyzing control systems. It provides a range of
functions and tools for modeling, simulation, analysis, and visualization of dynamic systems.
One of the major advantages of using MATLAB for control systems is its extensive library of
built-in functions and toolboxes. MATLAB provides various control toolboxes such as Control
System Toolbox, Simulink Control Design, and Robust Control Toolbox that offer pre-built
algorithms, blocks, and models for designing and analyzing control systems.