Document From ? 2
Document From ? 2
LAB MANUAL
Submitted By:
Laiba Yousaf
( 2125115017 )
Submitted to:
Objectives: This lab gives an introduction to MATLAB in the first part. In second part, the lab
also provides tutorial of polynomials, plotting and programming aspect of MATLAB from control
systems view point.
List of Equipment/Software:
Following equipment/software is required:
MATLAB
Introduction to MATLAB:
For specific technologies, MATLAB provides toolboxes, which add to the basic MATLAB
functionality. Some toolboxes include Image Processing Toolbox, Statistics Toolbox, Neural
Network Toolbox, Fuzzy Logic Toolbox, Signal Processing Toolbox, Wavelet Toolbox, Financial
Toolbox, Bioinformatics Toolbox, Database Toolbox.
MATLAB's graphical interface is written in Java and should be look similar on any OS. It is
divided into 4 main parts:
1. Command Window—this is where you type commands. Output or error messages usually
appear here too.
2. Workspace window—as you define new variables, they should be listed here.
3. Command History window—this is where past commands are remembered. If you want
to re-run a previous command or to edit it you can drag it from this window to the command
window or double click to re-run it.
4. Current Directory window—shows the files in the Current Directory.
Basic Operation:
We can also create this vector by typing x=1:10. The vector (1 1.1 1.2 1.3 1.4 1.5) can be created
by typing x=[ 1 1.1 1.2 1.3 1.4 1.5 ] or by typing x=1:0.1:1.5.
i.e., rows are separated with semi-colons. If we want to use a specific element in a vector or a
matrix, study the following example:
Example:
x=[10 20 30]
A=[ 1 2 3 ; 4 5 6 ; 7 8 9]
x(2)
A(3,1)
Here we extracted the second element of the vector by typing the variable and the position within
parentheses. The same principle holds for matrices; the first number specifies the row of the matrix,
and the second number specifies the column of the matrix. Note that in MATLAB the first index
of a vector or matrix starts at 1, not 0 as is common with other programming languages.
If the matrices (or vectors which are special cases of a matrices) are of the same dimensions then
matrix addition, matrix subtraction and scalar multiplication works just like we are used to.
Example: Type
x=[1 2 3]
y =[4 5 6]
a=2
x+y
x-y
a*x
If want to apply an operation such as squaring each element in a matrix we have to use a dot .
before the operation we wish to apply. Type the following commands in MATLAB.
x=1:10
x. ^2
A=[1 2 3 ; 4 5 6 ; 7 8 9 ]
A.^2
A^2
and observe the result. The dot allows us to do operations elementwise. All built-in functions
such as sin, cos, exp and so on automatically act elementwise on a matrix. Type
y=pi*y
sin(y)
Colon Operator:
b=
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
If you only want a subset of b, for instance, the inner square, you can type: b(2:3,2:3)
ans =
6 7
10 11
Let's break down the b(2:3,2:3) a little. MATLAB is accessing row two to three (2:3) inclusive
and column two to three (2:3) inclusive. Other than that, we are looking at the
same (row,column) notation that you are used to.
Outside of the subscript notation, the colon operator will create a row vector containing the integers
in the range specified. For instance, typing 2:8 results in:
ans =
2 3 4 5 6 7 8
You can also specify an increment or decrement (as a middle argument) with the colon operator.
For instance, typing 1:2:8 results in:
ans =
1 3 5 7
In this case, the increment is 2. Effectively, you are getting all of the odd numbers between 1 and
8.
tell MATLAB not to display any output when you end a line with a semicolon ( ; ). This is
particularly useful when you generate large matrices or perform long scripted computations.
Polynomials in MATLAB:
Polynomial Overview:
MATLAB provides functions for standard polynomial operations, such as polynomial roots,
evaluation, and differentiation. In addition, there are functions for more advanced applications,
such as curve fitting and partial fraction expansion.
Symbolic Math Toolbox contains additional specialized support for polynomial operations.
This is the celebrated example Wallis used when he first represented Newton's method to the
French Academy. To enter this polynomial into MATLAB, use
>>p = [1 0 -2 -5];
Polynomial Roots:
>>r = roots(p)
r=
2.0946
-1.0473 + 1.1359i
-1.0473 - 1.1359i
By convention, MATLAB stores roots in column vectors. The function poly returns to the
polynomial coefficients:
>>p2 = poly(r)
p2 =
1 8.8818e-16 -2 -5
Polynomial Evaluation:
>>polyval(p,5)
ans =
110
It is also possible to evaluate a polynomial in a matrix sense. In this case the equation p(x) = x3 –
2x – 5 becomes p(X) = X3 – 2X – 5I, where X is a square matrix and I is the identity matrix.
>>X = [2 4 5; -1 0 3; 7 1 5];
>>Y = polyvalm(p,X)
Y=
377 179 439
111 81 136
490 253 639
c=
4 13 28 27 18
>>[q,r] = deconv(c,a)
q=
4 5 6
r=
0 0 0 0 0
Polynomial Derivatives:
The polyder function computes the derivative of any polynomial. To obtain the derivative of the
polynomial
>>p= [1 0 -2 -5]
>>q = polyder(p)
q=
3 0 -2
polyder also computes the derivative of the product or quotient of two polynomials. For example,
create two polynomials a and b:
>>a = [1 3 5];
>>b = [2 4 6];
Calculate the derivative of the product a*b by calling polyder with a single output argument:
>>c = polyder(a,b)
c=
8 30 56 38
Calculate the derivative of the quotient a/b by calling polyder with two output arguments:
>>[q,d] = polyder(a,b)
q=
-2 -8 -2
d=
4 16 40 48 36
Plotting on MATLAB:
MATLAB has an excellent set of graphic tools. Plotting a given data set or the results of
computation is possible with very few commands. The plot function has different forms depending
on the input arguments. If y is a vector, plot(y) produces a piecewise linear graph of the elements
of y versus the index of the elements of y. if we specify two vectors, plot(x,y) produces a graph of
y versus x. The basic MATLAB graphing procedure, for example in 2D, is to take a vector of x-
coordinates, x=(x1; : : : : : xn), and a vector of y-coordinates, y=(y1; : : : : : yn), locate the points
(xi; yi), with i = 1; 2; : : : : : n and then join them by straight lines.
You need to prepare x and y in an identical array form; namely, x and y are both row arrays or
column arrays of the same length. If x and y are both matrices, then they must have equal size.
The plot function plots columns of y versus columns of x. If one of x or y is a vector and the other
is a matrix, then the matrix must have dimensions such that one of its dimensions equals the vector
length. If the number of matrix rows equals the vector length, then the plot function plots each
matrix column versus the vector. If the number of matrix columns equals the vector length, then
the function plots each matrix row versus the vector. If the matrix is square, then the function plots
each column versus the vector. If one of x or y is a scalar and the other is either a scalar or a vector,
then the plot function plots discrete points. However, to see the points you must specify a marker
symbol, for example, plot(x,y,'o').
Plot(x,y):
>>x = [1 2 3 4 5 6];
y = [3 -1 2 4 5 1];
>>plot(x,y)
Create single line plot:
Create x as a vector of linearly spaced values between 0 and 2π. Use an increment
of π/100 between the values. Create y as sine values of x. Create a line plot of the data.
>>x = 0:pi/100:2*pi;
>>y = sin(x);
>>plot(x,y)
Define x as 100 linearly spaced values between −2π and 2π. Define y1 and y2 as sine and cosine
values of x. Create a line plot of both sets of data.
x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
figure
plot(x,y1,x,y2)
Specific line style:
Plot three sine curves with a small phase shift between each line. Use the default line style for
the first line. Specify a dashed line style for the second line and a dotted line style for the third
line.
x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
figure
plot(x,y1,x,y2,'--',x,y3,':')
Display markers at specific data points:
Create a line plot and display markers at every fifth data point by specifying a marker symbol
and setting the MarkerIndices property as a name-value pair.
x = linspace(0,10);
y = sin(x);
plot(x,y,'-o','MarkerIndices',1:5:length(y))
Stem(y):
stem(y) plots the data sequence, y, as stems that extend from a baseline along the x-axis. The data
values are indicated by circles terminating each stem. If y is a vector, then the x-axis scale ranges
from 1 to length(y). If y is a matrix, then stem plots all elements in a row against the same x value,
and the x-axis scale ranges from 1 to the number of rows in y.
stem(x,y) plots the data sequence, y, at values specified by X. The X and Y inputs must be vectors
or matrices of the same size. Additionally, X can be a row or column vector and Y must be a matrix
with length(x) rows. If x and y are both vectors, then stem plots entries in y against corresponding
entries in x. If x is a vector and y is a matrix, then stem plots each column of y against the set of
values specified by x, such that all elements in a row of y are plotted against the same value.
If x and y are both matrices, then stem plots columns of y against corresponding columns of x.
Create a stem plot of 50 data values between −2π and 2π.
figure
Y = linspace(-2*pi,2*pi,50);
stem(Y)
Plot two data series using a two-column matrix.
figure
X = linspace(0,2*pi,50)';
Y = [cos(X), 0.5*sin(X)];
stem(Y)
Plot 50 data values of cosine evaluated between 0 and 2π and specify the set of x values for the
stem plot.
figure
X = linspace(0,2*pi,50)';
Y = cos(X);
stem(X,Y)
Polynomial Curve Fitting:
The polyfit function finds the coefficients of a polynomial that fits a set of data in a least-squares
sense. If x and y are two vectors containing the x and y data to be fitted to a n-degree polynomial,
then we get the polynomial fitting the data by writing –
p = polyfit(x,y,n)
Example
Create a script file and type the following code.
x = [1 2 3 4 5 6]; y = [5.5 43.1 128 290.7 498.4 978.67]; %data
p = polyfit(x,y,4) %get the polynomial
% Compute the values of the polyfit estimate over a finer range,
% Compute the values of the polyfit estimate over a finer range,
% and plot the estimate over the real data values for comparison:
x2 = 1:.1:6;
y2 = polyval(p,x2);
plot(x,y,'o',x2,y2)
grid on
When you run the file, MATLAB displays the following result −
p=
4.1056 -47.9607 222.2598 -362.7453 191.1250
Plot Different Waveforms (sinewave, triangular wave, Saw tooth, Ramp) on MATLAB.
Code Screenshot
Waveforms
B-Introduction to Simulink and its components. Learn and IMITATE the
process to produce a sample model
Objective:
Partial Fractions:
The partial fraction expansion for F(s)=b(s)/a(s) can be found using the statement:
[r,p,k]=residue(b,a)
where r is residue, p roots of denominator and k direct quotient which is found by dividing
polynomials prior to performing a partial fraction expansion, In an example, the end result of the
Laplace transform solution of a differential expression is 32s/s(s+4)(s+8) we can find the partial
fraction of this solution by simply defining the numerator and denominator.
Num=32;
Den=[1 12 32 0];
[r,p,k]=residue(Num ,Den)
Creating Transfer Functions:
A transfer function can be expressed as nominator polynomial divided by a denominator
polynomial that is F(s)= N(s)/D(s). The nominator N(s) is represented by a row vector, numf, that
contains the coefficients of N(s). similarly the denominator of D(s) is represented by a row vector
,denf , that contains the coefficients of D(s). We form F(s) with the command
T=tf (numf, denf)
T is called a linear time invariant (LTI) object. This object or transfer function can be used as an
entity in other operations, such as addition or multiplication. We demonstrate with
F(s)= 10 (s2+3s+5)/(s2+s+2)
numf=10*[1 3 5];
denf=[1 1 2];
T=tf (numf, denf)
10s2+30s+50 / s2+s+2
Transfer Function:
Transfer Function nominator and denominator vectors can be converted between polynomial form
containing the coefficients and factored form containing the root. The MATLAB functions tf2zp
(numtf , dentf) , converts the denominator and nominator from coefficients to roots. The results
are in the form of vectors, we demonstrate this
F(s)=s2+s+3 / s3+ 2s2+s+10
Numtf = [1 1 3]
Dentf = [1 2 1 1 0]
[Numfzp,denfzp] = tf2zp(Numtf,Dentf)
Introduction to Simulink:
Simulink is a graphical extension to MATLAB for modeling and simulation of systems. One of
the main advantages of Simulink is the ability to model a nonlinear system, which a transfer
function is unable to do. Another advantage of Simulink is the ability to take on initial conditions.
When a transfer function is built, the initial conditions are assumed to be zero.
In Simulink, systems are drawn on screen as block diagrams. Many elements of block diagrams
are available, such as transfer functions, summing junctions, etc., as well as virtual input and output
devices such as function generators and oscilloscopes. Simulink is integrated with MATLAB and
data can be easily transferred between the programs.
Starting Simulink:
Simulink is started from the MATLAB command prompt by entering the following command:
simulink
Alternatively, you can hit the Simulink button at the top of the MATLAB window as shown here:
When it starts, Simulink brings up a single window, entitled Simulink Start Page which can be
seen here.
Once you click on Blank Model, a new window will appear as shown below.
Model Files:
In Simulink, a model is a collection of blocks which, in general, represents a system. In addition
to creating a model from scratch, previously saved model files can be loaded either from
the File menu or from the MATLAB command prompt. As an example, download the following
model file by right-clicking on the following link and saving the file in the directory you are
running MATLAB from.
simple.slx
Open this file in Simulink by entering the following command in the MATLAB command window.
(Alternatively, you can load this file using the Open option in the File menu in Simulink, or by
hitting Ctrl-O in Simulink).
simple
The following model window should appear.
A new model can be created by selecting New from the File menu in any Simulink window (or by
hitting Ctrl-N).
Basic Elements:
There are two major classes of items in Simulink: blocks and lines. Blocks are used to generate,
modify, combine, output, and display signals. Lines are used to transfer signals from one block to
another.
Blocks
There are several general classes of blocks within the Simulink library:
Sources: used to generate various signals
Sinks: used to output or display signals
Continuous: continuous-time system elements (transfer functions, state-space models, PID
controllers, etc.)
Discrete: linear, discrete-time system elements (discrete transfer functions, discrete state-space
models, etc.)
Math Operations: contains many common math operations (gain, sum, product, absolute value,
etc.)
Ports & Subsystems: contains useful blocks to build a system
Blocks have zero to several input terminals and zero to several output terminals. Unused input
terminals are indicated by a small open triangle. Unused output terminals are indicated by a small
triangular point. The block shown below has an unused input terminal on the left and an unused
output terminal on the right.
Lines
Lines transmit signals in the direction indicated by the arrow. Lines must always transmit signals
from the output terminal of one block to the input terminal of another block. On exception to this
is a line can tap off of another line, splitting the signal to each of two destination blocks, as shown
below.
Lines can never inject a signal into another line; lines must be combined through the use of a block
such as a summing junction.
A signal can be either a scalar signal or a vector signal. For Single-Input, Single-Output (SISO)
systems, scalar signals are generally used. For Multi-Input, Multi-Output (MIMO) systems, vector
signals are often used, consisting of two or more scalar signals. The lines used to transmit scalar
and vector signals are identical. The type of signal carried by a line is determined by the blocks on
either end of the line.
Simple Example:
The simple model consists of three blocks: Step, Transfer Function, and Scope. The Step is
a Source block from which a step input signal originates. This signal is transferred through
the line in the direction indicated by the arrow to the Transfer Function Continuous block.
The Transfer Function block modifies its input signal and outputs a new signal on a line to
the Scope. The Scope is a Sink block used to display a signal much like an oscilloscope.
There are many more types of blocks available in Simulink, some of which will be discussed later.
Right now, we will examine just the three we have used in the simple model.
Modifying Blocks:
A block can be modified by double-clicking on it. For example, if you double-click on the Transfer
Function block in the Simple model, you will see the following dialog box.
This dialog box contains fields for the numerator and the denominator of the block's transfer
function. By entering a vector containing the coefficients of the desired numerator or denominator
polynomial, the desired transfer function can be entered. For example, to change the denominator
to
When a simulation is performed, the signal which feeds into the scope will be displayed in this
window. Detailed operation of the scope will not be covered in this tutorial.
Running Simulations:
To run a simulation, we will work with the following model file:
simple2.slx
Download and open this file in Simulink following the previous instructions for this file. You
should see the following model window.
Before running a simulation of this system, first open the scope window by double-clicking on the
scope block. Then, to start the simulation, either select Run from the Simulation menu, click
the Play button at the top of the screen, or hit Ctrl-T.
The simulation should run very quickly and the scope window will appear as shown below.
Note that the step response does not begin until t = 1. This can be changed by double-clicking on
the step block. Now, we will change the parameters of the system and simulate the system again.
Double-click on the Transfer Function block in the model window and change the denominator
to:
[1 20 400]
Re-run the simulation (hit Ctrl-T) and you should see the following in the scope window.
Since the new transfer function has a very fast response, it compressed into a very narrow part of
the scope window. This is not really a problem with the scope, but with the simulation itself.
Simulink simulated the system for a full ten seconds even though the system had reached steady
state shortly after one second.
To correct this, you need to change the parameters of the simulation itself. In the model window,
select Model Configuration Parameters from the Simulation menu. You will see the following
dialog box.
There are many simulation parameters options; we will only be concerned with the start and stop
times, which tell Simulink over what time period to perform the simulation. Change Start
time from 0.0 to 0.8 (since the step doesn't occur until t = 1.0). Change Stop time from 10.0 to
2.0, which should be only shortly after the system settles. Close the dialog box and rerun the
simulation. Now, the scope window should provide a much better display of the step response as
shown below.
Post Lab Assignment:
1. Consider the two polynomials p(s) = s2 + 2s + 1 and q(s) = s + 1. Using MATLAB compute:
a. p(s) * q(s)
b. Roots of p(s) and q(s)
c. p(-1) and q(6)
Solution
a.
b.
c.
2. Use MATLAB command to find the partial fraction of the following:
(𝑠) = 2𝑠𝑠33+5𝑠
a. (𝑠) +3𝑠+6
+6𝑠22+11𝑠+6
(𝑠) = 𝑠2+2𝑠+3
b. 𝐴(𝑠) (𝑠+1)2
a.
b.
Comments: