Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lab 1-CS-Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

International Islamic University Islamabad

Faculty of Engineering & Technology


Department of Electrical Engineering

CONTROL SYSTEMS LAB

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems

Name of Student: ……………………………………

Registration No.: ……………………………………..

Date of Experiment: …………………………………

Submitted To: ………………………………………...

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 1
Objectives:
 Introduction to MATLAB, basic operations and plotting techniques in MATLAB.
 MATLAB programming, flow controls, functions and scripts writing using MATLAB.
 Introduction to Simulink tool for control systems.
Equipment Required:
 Personal Computer (PC)
 MATLAB software (updated)
Introduction to MATLAB:
MATLAB stands for MATRIX Laboratory. It is a computer program that combines
computation and visualization power, which makes it particularly useful tool for engineers.
MATLAB is an executive program, and a script can be made with a list of MATLAB
commands like other programming language. The system was designed to make matrix
computation particularly easy. MATLAB environment allows the user to:
 Manage variables
 Import and export data
 Perform calculations
 Generate plots
 Develop and manage files
MATLAB Interface:
Figure 1.1 shows the main interface of MATLAB software.

Figure 1.1

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 2
The main interface has three main windows.
i. Workspace: It contains all the defined variables data.
ii. Command History: It contains the list of all typed commands in the history.
iii. Command Window: It provides the main interface for the execution of commands. All
commands are entered in Command Window.
Getting Help in MATLAB:
MATLAB provides a run time help related to all commands, functions, toolboxes and
libraries. Help menu can be used by executing different help commands in command
window. Following is the summary of the help commands along with description.

Sr. MATLAB Description


No. Command
1 help help lists all primary help topics in the Command Window.
help topic help name displays the help text for the functionality specified
2
name by name, such as a function, method, class, or toolbox.

Defining variables in MATLAB:


Variables in MATLAB represent numerical quantities such as numbers, vectors, matrices
and others. Following things need to be observed for defining variables.
i. Name of the variable must start with a letter.
ii. Name of the variable contains only letters, digits, and the underscore “_”.
iii. MATLAB is case sensitive, i.e. one & ONE are different variables.
iv. Assignment statement is: variable = number; variable = 'expression';
v. The variable definition may be terminated using semicolon or without semi colon.
Using semi colon will hide the result upon execution of the variable command and
vice versa.
vi. The keyword “%” is written before any string/text to add comments in the code.
Example: (Declaration and Initialization of variables)
% var1, var2 and var3 are three different variables
>> var1 = 2
>> var2 = 4
>> var3 = 8;
Special variables:
Some variables in MATLAB are termed as special and they have specific meaning and
purpose of their use. Some of the special variables are listed below.

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 3
Sr. Special Description
No. Variable
1 ans It is the default variable name for the result.
2 eps ε = 2.2204e-016, smallest amount by which 2 numbers can differ.

3 pi It gives a value of 2.31416 (mathematical constant).


4 Inf on inf ∞, infinity.

5 NaN or nan Not a number.

MATLAB commands involving variables:


Sr. MATLAB
Description
No. Command
1 clc It clears the command window.
clear
2 It clears the variable name.
name
clear
3 It clears all variables; reset the default values of special variables.
all
4 clf It clears the current figure and the graph window.

5 who It lists the names of defined variables.


6 whos It lists the names and sizes of defined variables.

Vectors:
A one-dimensional array of numbers is referred as vector.
i. A row vector in MATLAB can be created by an explicit list, starting with a left square
bracket, entering the values separated by spaces (or commas) and closing the vector
with a right square bracket.
Example: (Creation of Row vector)
>> x = [0 0.25*pi 0.5*pi 0.75*pi pi]
ii. A column vector can be created the same way, and the rows are separated by
semicolons.
Example: (Creation of Column vector)
>> y = [0; 0.25*pi; 0.5*pi; 0.75*pi; pi]
Matrix:
A matrix array is two-dimensional, having both multiple rows and multiple columns. It is
defined by beginning with left square bracket and ending with right square bracket. Spaces or
commas are used to separate elements in a row. Semicolon is used to separate rows.
Example: (Creation of Matrices)
Let A is a 2 x 3 matrix, we can define it as:
>> A = [1 3 5;7 9 11]

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 4
Let B is a 3 x 3 matrix, we can define it as:
>> B = [2 4 6;8 10 12;14 16 18]
Some commonly used MATLAB commands:
(Note: A, B, C are matrices, and k, m, n, p are scalars)

Sr. MATLAB
Description
No. Command
1 A=zeros(n) It returns an n x n “matrix A” of zeros.

2 B=zeros(m,n) It returns an m x n “matrix B” of zeros.

3 A=ones(n) It returns an n x n “matrix A” of ones.

4 B=ones(m,n) It returns an m x n “matrix B” of ones.

5 A=eye(n) It returns an n x n identity “matrix A”.


It returns an m x n identity “matrix B” with ones on the main
6 B=eye(m,n)
diagonal and zero elsewhere.
7 A=rand(n) It returns an n x n “matrix A” of random numbers b/w 0 and 1.

8 B=rand(m,n) It returns an m x n “matrix B” of random numbers b/w 0 and 1.


It returns an n x n “matrix A” constructed from the
A = magic(n)
9 integers 1 through n2 with equal row and column sums. The
order n must be a scalar greater than or equal to 3
It returns a row vector [m, n] containing the number of rows (m) and
10 size(A)
columns (n) of matrix A.
11 B=A.^2 It squares each element of an m x n “matrix A”.

12 C=B' It determines the transpose of an m x n “matrix B”.


It adds m x n “matrix A” to m x n “matrix B” using element by
13 C=A+B
element operation.
It subtracts m x n “matrix B” from m x n “matrix A” using
14 C=A-B
element by element operation.
It multiplies m x n “matrix A” with m x n “matrix B” using
15 C=A.*B
element by element operation.
It divides m x n “matrix A” by m x n “matrix B” using element
16 C=A./B
by element operation.
C is the inner product of matrices “A and B”. If A is an m x p
17 C=A*B
and B is a p x n matrix, then C is an m x n matrix.
18 B=k*A It multiplies an (m x n) “matrix A” with “scalar k”.
det(B)
19 A must be square It computes and returns the determinant of an n x n “matrix B”.
matrix
inv(B)
20 A must be a square It computes and returns the inverse of an n x n “matrix B”.
matrix
21 rank(C) It determines and returns the rank of a “matrix C”.

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 5
Plotting in MATLAB:
Plotting is generally used to show the behavior of a system, equation, relation or
mathematical interpretation by graph. MATLAB provides different plotting techniques for
different simulation environment. Most common plotting command is “plot(x,y)”, where
x represents the variable name and y represents the axis points against which, x will be
plotted.
Plotting a Point:
Syntax: plot (variable_name, ‘symbol’)
Example: (Plotting a complex number)
>> z = 1 + 0.5j;
>> plot (z, ‘.’)
Commands for “axes”:

Sr.
Command Description
No.
1 axis ([xmin xmax ymin ymax]) It sets the limits for the x and y axis of the current axes.
“axis auto” sets MATLAB default behavior to compute
the current axes limits automatically, based on the
minimum and maximum values of x, y, and z data. You
2 axis (auto) can restrict this automatic behavior to a specific axis. For
example, axis 'auto x' computes only the x-axis limits
automatically; axis 'auto yz' computes the y- and z-axis
limits automatically.
“axis square” makes the current axes region square (or
cubed when three-dimensional). This option adjusts the
3 axis square x-axis, y-axis, and z-axis so that they have equal lengths
and adjusts the increments between data units
accordingly.
“axis equal” sets the aspect ratio so that the data units are
the same in every direction. The aspect ratio of the x-, y-,
4 axis equal
and z-axis is adjusted automatically according to the
range of data units in the x, y, and z directions.
“axis normal” automatically adjusts the aspect ratio of
5 axis normal the axes and the relative scaling of the data units so that
the plot fits the figure's shape as well as possible.

6 axis off “axis off” turns off all axis lines, tick marks, and labels.

7 axis on “axis on” turns on all axis lines, tick marks, and labels.

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 6
Plotting Curves:
 plot (x,y) – creates a 2D line plot of the data in y versus the corresponding values of x.
If x and y are both vectors, then they must have equal length and MATLAB plots y versus
x. If x and y are both matrices, then they must have equal size and MATLAB plots
columns of y versus columns of x.
 semilogx (x,y) – generates a semilogarithmic plot with logarithmic x-axis and linear y-
axis.
 semilogy (x,y) – generates a semilogarithmic plot with logarithmic y-axis and linear x-
axis.
 loglog(x,y) – generates a logarithmic plot using logarithmic scales for both x and y.

Multiple Curves:
 plot(x1, y1,..., xn, yn) – plots multiple x, y pairs using the same axes for all lines.
 legend (‘string1’, ‘string2’,…) – displays a legend in the current axes using the specified
strings to label each set of data.

Multiple Figures:
 figure(n) – used in creation of multiple plot windows. Place this command before the
plot() command, and the corresponding figure will be labeled as figure “n”.
 close – closes the figure “n” window.
 close all – closes all the figure windows.

Subplots:
 subplot (m,n,p) – divides the current figure into an m-by-n grid and creates an axes in the
grid position specified by p. MATLAB numbers its grids by row, such that the first grid is
the first column of the first row, the second grid is the second column of the first row, and
so on.

Adding new curves to the existing graph:


 hold on retains the current graph and adds another graph to it. MATLAB adjusts the axes
limits, tick marks, and tick labels as necessary to display the full range of the added
graph.
 hold off resets hold state to the default behavior, in which MATLAB clears the existing
graph and resets axes properties to their defaults before drawing new plots.

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 7
Grids and Labels:
Sr.
Command Description
No.
1 grid on grid on adds major grid lines to the current axes.
2 grid off grid off removes all grid lines from the current axes.
title(‘text’) adds the title consisting of a string (text), at
3 title(‘text’)
the top and in the center of the current axes.
xlabel(‘text’) labels the x-axis of the current axes with
4 xlabel(‘text’)
the string (text), written inside commas.
ylabel(‘text’) xlabel(‘text’) labels the y-axis of the current axes with
5
the string (text), written inside commas.

text (x,y,‘text’)
adds the string in quotes to the location specified by the
6
point (x,y), x and y must be numbers of class double.

Example: (Plotting a sine wave)


>> clc
>> clear all
>> close all
>> t = 0: 0.01:1;
>> y = sin(2*pi*t);
>> subplot(2,1,1), plot(t,y);
>> title('Original Sine Wave');
>> xlabel('Time'), ylabel('Amplitude'), grid on;
>> subplot(2,1,2), plot(y,t);
>> title('Rotated Sine Wave');
>> xlabel('Amplitude'), ylabel('Time'), grid on;

Figure 1.2

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 8
Example: (Plotting a polynomial function using different scales)
Plot the given polynomial using linear/linear scale, log/linear scale, linear/log scale, &
log/log scale.
y = x3 - 2x2 + 5x + 7
Solution:
>> clc
>> clear all
>> close all
>> x = linspace (0, 10, 200);
% It generates 200 points (n), 0 is the starting point (x1) whereas
10 is the ending point (x2).
% The spacing between the points is 0.0503 (x2-x1)/(n-1).
>> y = x.^3 - 2*(x.^2) + 7*x + 9; % It generates the polynomial
% Plotting the polynomial using different scales
>> subplot(2,2,1), plot(x,y);
>> title('Polynomial, linear/linear scale');
>> xlabel('x'), ylabel('y'), grid on;
>> subplot(2,2,2), semilogx(x,y);
>> title('Polynomial, log/linear scale');
>> xlabel('x'), ylabel('y'), grid on;
>> subplot(2,2,3), semilogy(x,y);
>> title('Polynomial, linear/log scale');
>> xlabel('x'), ylabel('y'), grid on;
>> subplot(2,2,4), loglog(x,y);
>> title('Polynomial, log/log scale');
>> xlabel('x'), ylabel('y'), grid on;

Figure 1.3

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 9
Representing Polynomials:
MATLAB represents polynomials as row vectors containing coefficients ordered by
descending powers. For example, consider the equation:
𝒑(𝒙) = 𝒙𝟑 − 𝟐𝒙 − 𝟓
To enter this polynomial into MATLAB, use
>> p = [1 0 -2 -5];
Polynomial Roots:
The roots function calculates the roots of a polynomial:

>> r = roots (p)


By convention, MATLAB stores roots in column vectors. The function poly returns to the
polynomial coefficients:
>> p2 = poly(r)
Note: poly and roots are inverse functions.
Polynomial Evaluation:
The polyval function evaluates a polynomial at a specified value. To evaluate p at s = 5, use
>> polyval(p,5)

Scripts:
Scripts, which do not accept input arguments or return output arguments. They operate
on data in the workspace. MATLAB provides a full programming language that enables you
to write a series of MATLAB statements into a file and then execute them with a single
command. You write your program in an ordinary text file, giving the file a name of
‘filename.m’. The term you use for ‘filename’ becomes the new command that MATLAB
associates with the program. The file extension of .m makes this a MATLAB “M-file”.
Example: (Script Writing)
% create 50 random numbers and plot them in MATLAB
>> r = rand(1,50);
>> plot (r);
Functions:
Functions are M-files that can accept input arguments and return output arguments. The
names of function and M-file should be the same. Functions operate on variables within their
own workspace, separate from the workspace you access at the MATLAB command prompt.
Internal variables are local to the function.

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 10
Example: Compute the factorial of an input number using a function in MATLAB?
Solution:
% M-file:
function f = fact(n)
% function definition; fact is the name of function, f is the output
to be returned, n is the input to the function
f = prod(1:n); % function body, “prod (1:n)” command finds the
factorial of the number ‘n’
% Calling the “fact” function in Command Window:
>> f = fact(5);
f =
120
Flow Control:
Conditional Control -- if, else:
This section covers those MATLAB functions, which provide conditional program
control if, else and elseif. The “if” statement evaluates a logical expression and executes a
group of statements when the expression is true. The optional “elseif and else” keywords
provide the execution of alternate groups of statements. An “end” keyword, which matches
the if, terminates the group of statements. The groups of statements are delineated by four
keywords — no braces or brackets are involved as given below.
if <condition>
<statements>;
elseif <condition>
<statements>;
else
<statements>;
end
Switch and Case:
The switch statement executes groups of statements based on the value of a variable or
expression. The keywords “case” and “otherwise” delineate the groups. Only the first matching
case is executed. The syntax is as follows:
switch <condition or expression>
case <condition>
<statements>;
case <condition>
otherwise
<statements>;
end

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 11
Note: Unlike the C language switch statement, MATLAB switch does not fall through. If the first
case statement is true, the other case statements do not execute. Therefore, break statements are
not required.
“for” Loop:
The ‘for’ loop, is used to repeat a group of statements for a fixed, predetermined number of
times. A matching ‘end’ delineates the statements. The syntax is as follows:
for <index> = <starting number>:<step or increment>:<ending number>
<statements>;
end
Example: (for loop)
s = 0;
for i = 1:10; % increment of 1
s = s+1;
end
disp (s);

“while” Loop:
The ‘while’ loop, repeats a group of statements indefinite number of times under control
of a logical condition. Therefore, a while loop executes at-least once before it checks the
condition to stop the execution of statements. A matching “end” delineates the statements. The
syntax of the “while” loop is as follows:
while <condition>

<statements>;
end
Example: (while loop)
% M-file:
function mysum = sumTill(n) % a function that sums numbers from 1 to n
mysum = 0;
counter = 1;
while (counter <= n)
mysum = mysum + counter;
counter = counter + 1;
end
%Calling the “sumTill” function in Command Window:
>> mysum = sumTill(6)
s =
21

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 12
Logical Operators:
Logical operators can be used to compare a scalar value with an array or for comparing
arrays. The logical data type represents true or false states using the numbers 1 and 0,
respectively. Certain MATLAB functions and operators return logical values to indicate
fulfillment of a condition. The use of these operators is illustrated through examples.
Examples:
>> A=[1 2;3 4];
>> B=[1 7;0 9];
Logical NOT Operation “~” Logical Less than or Greater than Operation

>> ~A >> ~B >> A<B >> A>B


ans = ans = ans = ans =
0 0 0 0 0 1 0 0
0 0 1 0 0 1 1 0
Logical Equalization “==” Logical OR Operation “|”
>> A==B >> A|B
ans = ans =
1 0 1 1
0 0 1 1
Logical AND Operation “%” Logical XOR
>> A&B >> xor(A,B)
ans = ans =
1 1 0 0
0 1 1 0

Introduction to 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. It provides an interactive
graphical environment and a customizable set of block libraries that let you accurately design,
simulate and implement the signal processing, communications, power electronics, control
and other time-varying systems. The blocks are grouped into libraries, by general classes of
functions.
 Step, Signal and Pulse Generator can be found in Sources library.
 Display, Scope, and To Workspace blocks can be found in Sinks library.
 Integrators, Derivative, PID and Transfer Function etc are in the Continuous library.
 Mathematical functions such as Sum, Add, Subtract, Product and Gain are in Math library.

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 13
To make a simulation model in Simulink, follow these steps:
a. Create a new Simulink model (window) and drag the needed blocks from their library
folders to that window.
b. Arrange these blocks in an orderly way corresponding to the equations to be solved.
c. Interconnect the blocks by dragging the cursor from the output of one block to the input
of another block.
d. 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.
e. It is necessary to specify a stop time for the solution. This is done by clicking on the
Simulation > Model Configuration Parameters tab. At the Simulation > Model
Configuration 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. The type of solver can also be
selected (ode45, ode23 etc). Remember that solvers are numerical integration algorithms
that compute the system dynamics over time using information contained in the model.
f. After the completion of Simulink model, save it and press the Run button to simulate.

Implementation of Different Systems using MATLAB/Simulink:


Example 1: Analyze the Signal Generator and Repeating Sequence Stair.

Figure 1.4

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 14
Example 2: Analyze the Step input, Gain and Summing Junction.

Figure 1.5
Example 3: Analyze the Pulse Generator, Differentiator and Integrator

Figure 1.6
Example 4: Find the solution of a given differential equation using MATLAB/Simulink?
Given: (Initial value problem in case of distinct real roots)
𝒚̈ + 𝒚̇ − 𝟐𝒚 = 𝟎 (1.1)
𝒚(𝟎) = 𝟒; 𝒚̇ (𝟎) = −𝟓; (1.2)
Solution using MATLAB code:
Step 1: General Solution
The characteristics equation is,
𝝀𝟐 + 𝝀 − 𝟐 = 𝟎
Its roots are:
𝟏 𝟏
𝝀𝟏 = (−𝟏 + √𝟗) = 𝟏 and 𝝀𝟐 = (−𝟏 − √𝟗) = −𝟐
𝟐 𝟐
The general solution can be written as:
𝒚(𝒙) = 𝒄𝟏𝒆𝒙 + 𝒄𝟐𝒆−𝟐𝒙 (1.3)

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 15
Step 2: Particular Solution
𝒚̇ (𝒙) = 𝒄𝟏𝒆𝒙 − 𝟐𝒄𝟐𝒆−𝟐𝒙 , (1.4)
Using Eq. (1.3) and (1.4), we can write:
𝒚(𝟎) = 𝒄𝟏 + 𝒄𝟐 = 𝟒 (1.5)
𝒚̇ (𝟎) = 𝒄𝟏 − 𝟐𝒄𝟐 = −𝟓 (1.6)
After solving Eq. (1.5) and (1.6), we can obtain: 𝒄𝟏 = 𝟏 and 𝒄𝟐 = 𝟑.
Finally, we can write:
𝒚(𝒙) = 𝒆𝒙 + 𝟑𝒆−𝟐𝒙
𝒚̇ (𝒙) = 𝒆𝒙 − 𝟔𝒆−𝟐𝒙
𝒚̈ (𝒙) = 𝒆𝒙 + 𝟏𝟐𝒆−𝟐𝒙
Step 3: MATLAB Code
>> clc
>> clear all
>> close all
>> x=0:0.001:1
>> y=exp(x)+3*exp(-2*x);
>> subplot(3,1,1), plot(x,y);
>> title('y');
>> xlabel('Time'), ylabel('y(t)'), grid on;
>> y1=exp(x)-6*exp(-2*x);
>> subplot(3,1,2), plot(x,y1);
>> title('y1');
>> xlabel('Time'), ylabel('y1(t)'), grid on;
>> y2=exp(x)+12*exp(-2*x);
>> subplot(3,1,3), plot(x,y2);
>> title('y2');
>> xlabel('Time'), ylabel('y2(t)'), grid on;

Figure 1.7

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 16
Solution using MATLAB/Simulink:
Figure 1.8 shows the Simulink diagram to obtain the solution of given differential equation
(Eq. 1.1).

Figure 1.8
Figure 1.9 shows the desired response “y(t)”, which begins at 4 with a negative slope (-5, but
note that the axes have different scales) in agreement with the initial condition.

Figure 1.9

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 17
Exercise Problems

Question No. 1: In MATLAB, use “for” or “while” loop to convert celsius temperature into
fahrenheit temperature using following equation.
9
Tf = ( ∗ Tc) + 32
5
Use initial celsius temperature = 0, increment = 10, final celsius temperature = 200.
Question No. 2: Solve the system of three linear equations with three unknowns (x1, x2, x3 )
using matrix level programming in MATLAB. Hint: Use linsolve command to solve the
linear system of equations.
3𝑥1 + 2𝑥2 − 𝑥3 = 10
−𝑥1 + 3𝑥2 + 2𝑥3 = 5
𝑥1 − 𝑥2 − 𝑥3 = −1
Question No. 3: Implement the following system (Figure 1.10) using MATLAB/Simulink.

Figure 1.10
Question No. 4: Implement the analog to digital converter (ADC) given in Figure 1.11 using
MATLAB/Simulink.

Figure 1.11

Experiment No. 1: Introduction to MATLAB and Simulink for Control Systems Page 18

You might also like