0% found this document useful (0 votes)
68 views33 pages

Introduction To Matlab and Simulink

The document provides an overview of using MATLAB for control systems experiments. It outlines the objectives of experiment 1 as introducing MATLAB for matrix manipulation, plotting, and modeling differential equations in Simulink. The document then describes the MATLAB environment including the command window, workspace, help system, and basic operations for variables, built-in functions, arrays, vectors, matrices, and linear algebra operations.

Uploaded by

moiz
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
68 views33 pages

Introduction To Matlab and Simulink

The document provides an overview of using MATLAB for control systems experiments. It outlines the objectives of experiment 1 as introducing MATLAB for matrix manipulation, plotting, and modeling differential equations in Simulink. The document then describes the MATLAB environment including the command window, workspace, help system, and basic operations for variables, built-in functions, arrays, vectors, matrices, and linear algebra operations.

Uploaded by

moiz
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 33

Department of Electrical Engineering

Faculty of Engineering & Applied Sciences


Riphah International University, Islamabad, Pakistan

Program: B.Sc. Electrical Engineering Semester: VI


Subject: EE-345 Linear Control System Date: ………

Experiment No. 1: Using MATLAB for Control Systems

OBJECTIVES: Inquiry Level = 1

 To provide an introduction to MATLAB in terms of Matrix manipulation &


plotting in MATLAB
 An Overview of Simulink to model differential equation.

Name: ABDUL MOIZ BASHIR Sap ID:22961

Performance Work Ethics

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Taking
Ability to Conduct Responsibility/Sharing
Experiment
5 5
knowledge

Total Marks

Remarks (if any): ………………………………….

Name & Signature of faculty: …………………………………


The MATLAB Environment
The MATLAB Environment consists of the following main parts:
 Command Window
 Command History
 Workspace
 Current Folder
 Editor

Below we see the MATLAB environment:


Command Window
The Command Window is the main window in MATLAB. Use the Command Window to
enter
Variables and to run functions and M-files scripts (more about m-files later).

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.

You could also use the following command


>>who
This command list all the commands used
The command clear will clear all the variables in your workplace.
>>clear
Using the Help System in MATLAB
The Help system in MATLAB is quite comprehensive, so make sure you are familiar with
how the help system works.

When clicking the “Help” button, the following window appears:

You may also type “Help” in the Command window:

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

Naming a Variable Uniquely:


To avoid choosing a name for a new variable that might conflict with a name already in
use,check for any occurrences of the name using the which command:
which-all variablename
>>which -all pi
built-in (C:\Matlab\R2007a\toolbox\matlab\elmat\pi)
You may also use the iskeyword command. This command causes MATLAB to list all
reserved names.
>>iskeyword
ans =
'break'
'case'
'catch'
'classdef'
'continue'
'else'
'elseif'
'end'
'for'
'function'
'global'
'if'
'otherwise'
'persistent'
'return'
'switch'
'try'
'while'
Note! You cannot assign these reserved names as your variable names.
TASK 1
Type the following in the Command window:
>>y=16;
>>z=3;
>>y+z

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 Clear variables and >>clear


functions from memory. >>clear x
size Size of arrays, matrices >>x=[1 2 ; 3 4];
>>size(A)
length Length of a vector >>x=[1:1:10];
>>length(x)
disp Display text or array >>A=[1 2;3 4];
>>disp(A)
plot This function is used to >>x=[1:1:10];
create a plot >>plot(x)
>>y=sin(x);
>>plot(x,y)
max Find the largest number >>x=[1:1:10]
in a vector >>max(x)
mean Average or mean value >>x=[1:1:10]
>>mean(x)

Task 2: Statistics functions


Create a random vector with 100 random numbers between 0 and 100. Find the minimum
value, the maximum value, the mean using some of the built-in functions in MATLAB
listed above.

Write the code in the box.


clc;

clear all;

close all;

%ABDUL MOIZ BASHIR-22961%

% Generate a random vector with 100 random numbers between 0 and 100

random_vector = rand(1,100)*100;

% Find the minimum value using the min() function

min_value = min(random_vector);

% Find the maximum value using the max() function

max_value = max(random_vector);

% Find the mean using the mean() function

mean_value = mean(random_vector);

Arrays; Vectors and Matrices:


Matrices and vectors (Linear Algebra) are the basic elements in MATLAB and also the
basic elements in control design theory. So it is important you know how to handle vectors
and matrices in MATLAB.
In MATLAB we type vectors and matrices like this:

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.

Task 3: Vectors and Matrices


Type the following vector in the Command window:

[]
1
x= 2
3

Type the following matrix in the Command window:

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;

%ABDUL MOIZ BASHIR-22961%

% Define the vector x

x = [1; 2; 3];

% Define the matrix A

A = [0 1; -2 -3];

% Define the matrix B

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)

% Find the second row of matrix B

B(2, :)

% Find the third column of matrix B

B(:, 3)

Deleting Rows and Columns:


Given:

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]

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.

det Find the determinant of >>A=[1 2; 3 4]


a square matrix >>det(A)
inv Find the inverse of a >>A=[1 2; 3 4]
square matrix >>inv(A)
eig Find the eigenvalues of >>A=[1 2; 3 4]
a square matrix >>eig(A)
ones Creates an array or >>ones(2)
matrix with only ones >>ones(2,1)
eye Creates an identity >>eye(2)
matrix
diag Find the diagonal >>A=[1 2; 3 4]
elements in a matrix >>diag(A

Matrices
Given a matrix 𝐴:

[
A= 0 1
−2 −3 ]
>> A=[0 1;-2 -3]

A =
0 1
-2 -3

The Transpose of matrix 𝐴:


>> A'

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

Write your code for each task

A+ B %ABDUL MOIZ BASHIR-22961%

% Define the matrices A, B, and C

A = [0, 1; -2, -3];

B = [1, 0; 3, -2];

C = [1, -1; 2, -2];

% Find A + B

A_plus_B = A + B

A−B %ABDUL MOIZ BASHIR-22961%

% Define the matrices A, B, and C

A = [0, 1; -2, -3];

B = [1, 0; 3, -2];

C = [1, -1; 2, -2];

% Find A - B

A_minus_B = A – B

A
T %ABDUL MOIZ BASHIR-22961%

% Define the matrices A, B, and C

A = [0, 1; -2, -3];

B = [1, 0; 3, -2];

C = [1, -1; 2, -2];

% Find A^T
A_transpose = A'

diagA , diag¿ ) %ABDUL MOIZ BASHIR-22961%

% Define the matrices A, B, and C

A = [0, 1; -2, -3];

B = [1, 0; 3, -2];

C = [1, -1; 2, -2];

% Find diag(A)

diag_A = diag(A)

% Find diag(B)

diag_B = diag(B)

A
−1 %ABDUL MOIZ BASHIR-22961%

% Define the matrices A, B, and C

A = [0, 1; -2, -3];

B = [1, 0; 3, -2];

C = [1, -1; 2, -2];

% Find A^-1

A_inverse = inv(A)

detA , det ( B) %ABDUL MOIZ BASHIR-22961%

% Define the matrices A, B, and C

A = [0, 1; -2, -3];

B = [1, 0; 3, -2];

C = [1, -1; 2, -2];

% Find det(A)

det_A = det(A)

% Find det(B)

det_B = det(B)
% Define the matrices A, B, and C

A = [0, 1; -2, -3];

B = [1, 0; 3, -2];

C = [1, -1; 2, -2];

% Find det(AB)

det_AB = det(A*B)

eigA %ABDUL MOIZ BASHIR-22961%

% Define the matrices A, B, and C

A = [0, 1; -2, -3];

B = [1, 0; 3, -2];

C = [1, -1; 2, -2];

% Find eig(A)

eig_A = eig(A)

Solving Linear Equations

MATLAB can easily be used to solve a large amount of linear equations using built-in
functions.

Task 5: Linear Equations

Given the equations:


x 1+ 2 x 2=5
3 x 1+ 4 x 2=6
Set the equations on the following form:
Ax=b
→ Find 𝐴 and 𝑏 and define them in MATLAB.
Solve the equations, i.e., find x 1 , x 2, using MATLAB. It can be solved like this:
−1
Ax=b → x= A b
CODE:
clc;

close all;

clear all;

%ABDUL MOIZ BASHIR-22961%

% Define A and b

A = [1, 2; 3, 4];

b = [5; 6];

% Find the inverse of A

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)

plot Generates a plot. >X = clc;


plot(y) plots the [0:0.01:1]; close all;
columns of y >Y = X.*X;
>plot(X, Y) clear all;
against the
Indexes of the X = [0:0.01:4];
columns. Y = X.*X;
plot(X, Y)
figure Create a new >>figure
figure window >>figure(1)

subplot Create subplots >>subplot(2, clc;


in a Figure. 2,1) close all;
subplot(m,n,p) or
subplot(mnp), clear all;
breaks the Figure X = [0:0.01:4];
window into an
m-by-n matrix of Y = X.*X;
small axes, subplot(2,1,1);
Selects the p-th
plot (X,Y)
axes for the
current plot. The Y = X+X;
axes are counted
subplot(2,1,2);
along the top
row of the Figure plot (X,Y)
window, then the
second row,
etc.
grid Creates grid >>grid
lines in a plot. >>grid on
“grid on” adds >>grid off
major grid lines
to the current
plot.
“grid off”
removes major
and minor grid
lines from the
current
plot.
axis Control axis >>axis([xmin
scaling and xmaxyminymax
appearance. ])
“axis([xminxma >>axis off
xymin >>axis on
ymax])” sets the
limits for the x-
and y-axis of the
current axes.

title Add title to >>title('thi


current plot s is a
title('string') title')

xlabel Add xlabel to >>xlabel('ti


current plot me')
xlabel('string')

ylabel Add ylabel to >>ylabel('te


current plot mperature')
ylabel('string')
legen Creates a legend >>
d in the corner (or legend('temp
at a specified erature')
position) of the
plot

hold Freezes the >>hold on


current plot, so >>hold off
that additional
plots can be
overlaid

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

GAIN (Math library)


A gain block is shown by a triangular symbol, with the gain expression written inside if it
will fit. If not, the symbol - k - is used. The value used in each gain block is established in a
dialog box that appears if the user double-clicks on its block.
INTEGRATOR (Continuous library)
The block for an integrator as shown below looks unusual. The quantity 1/s comes from the
Laplace transform expression for integration. When double-clicked on the symbol for an
integrator, a dialog box appears allowing the initial condition for that integrator to be
specified. It may be implicit, and not shown on the block, as in Figure (a). Alternatively, a
second input to the block can be displayed to supply the initial condition explicitly, as in part
(b) of Figure 3. Initial conditions may be specific numerical values, literal variables, or
algebraic expressions.

CONSTANTS (Source library)


Constants are created by the Constant block, which closely resembles Figure 4. Double clicking
on the symbol opens a dialog box to establish the constant’s value. It can be a
number or an algebraic expression using constants whose values are defined in the workspace
and are therefore known to MATLAB.

STEP (Source library)


A Simulink block is provided for a Step input, a signal that changes (usually from zero) to a
specified new, constant level at a specified time. These levels and time can be specified
through the dialog box, obtained by double-clicking on the Step block
SIGNAL GENERATOR (Source library)
One source of repetitive signals in Simulink is called the Signal Generator. Double-clicking
on the Signal Generator block opens a dialog box, where a sine wave, a square wave, a ramp
(sawtooth), or a random waveform can be chosen. In addition, the amplitude and frequency
of the signal may be specified. The signals produced have a mean value of zero. The
repetition frequency can be given in Hertz (Hz), which is the same as cycles per second, or in
radians/second.

SCOPE (Sinks library)


The system response can be examined graphically, as the simulation runs, using the Scope
block in the sinks library. This name is derived from the electronic instrument, oscilloscope,

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.

You might also like