0% found this document useful (0 votes)
365 views

Lab Report Matlab

This document provides an introduction to MATLAB for control systems. It discusses MATLAB's capabilities for managing variables, importing/exporting data, performing calculations, generating plots, and developing files. It then covers various MATLAB commands and functions for defining variables and matrices, plotting graphs, solving systems of linear equations, representing and operating on polynomials, and more. The document contains exercises for students to practice these MATLAB skills.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
365 views

Lab Report Matlab

This document provides an introduction to MATLAB for control systems. It discusses MATLAB's capabilities for managing variables, importing/exporting data, performing calculations, generating plots, and developing files. It then covers various MATLAB commands and functions for defining variables and matrices, plotting graphs, solving systems of linear equations, representing and operating on polynomials, and more. The document contains exercises for students to practice these MATLAB skills.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

SECTION-D

MATLAB
Experiment No. 1
Using MATLAB for Control Systems
Objectives:
This lab provides an introduction to MATLAB in the first part. The lab also provides tutorial of
polynomials and script writing aspects of MATLAB from control systems view point.
List of Equipment/Software:
Following equipment/software is required: MATLAB
Deliverables:
 Observations and solutions to exercises provided at the end of each part of Lab 1
 Oral verification of results
Part I: Introduction to MATLAB
Objective:
The objective of this exercise will be to introduce you to the concept of mathematical programming
using the software called MATLAB. We shall study how to define variables, matrices etc, see how
we can plot results and write simple MATLAB codes.
What is MATLAB ?
MATLAB is a computer program that combines computation and visualization power that makes
it particularly useful tool for engineers. It is an executive program, and a script can be made with
a list of MATLAB commands like other programming language. MATLAB Stands for MATrix
LABoratory. The system was designed to make matrix computation particularly easy. The
MATLAB environment allows the user to:
 manage variables
 import and export data
 perform calculations
 generate plots
 develop and manage files for use with MATLAB

Display Windows:
When you start MATLAB, following windows may appear:
Besides these, following two windows are of importance:

Graphic (Figure) Window:

 Displays plots and graphs


 Created in response to graphics commands.

M-file editor/debugger window:

 Create and edit scripts of commands called M-files.

Getting Help:

Type one of following commands in the command window:

 help – lists all the help topic


 help topic – provides help for the specified topic
 help command – provides help for the specified command
 help help – provides information on use of the help command
 helpwin – opens a separate help window for navigation
 lookfor keyword – Search all M-files for keyword

Variables:

Variable names:

 Must start with a letter


 May contain only letters, digits, and the underscore “_”

Matlab is case sensitive, i.e. one & OnE are different variables. Matlab only recognizes
the first 31 characters in a variable name. Assignment statement:
 Variable = number;
 Variable = expression;

NOTE: when a semi-colon ”;” is placed at the end of each command, the result is not displayed.
Special variables:
 ans : default variable name for the result
 pi: 𝜋� = 3.1415926…………
 eps: 𝜀�= 2.2204e-016, smallest amount by which 2 numbers can differ.
 Inf or inf : ∞, infinity
 NaN or nan: not-a-number
Commands involving variables:
 who: lists the names of defined variables
 whos: lists the names and sizes of defined variables
 clear: clears all varialbes, reset the default values of special variables.
 clear name: clears the variable name
 clc: clears the command window
 clf: clears the current figure and the graph window.
Vectors:
A row vector in MATLAB can be created by an explicit list, starting with a left bracket, entering
the values separated by spaces (or commas) and closing the vector with a right bracket. A column
vector can be created the same way, and the rows are separated by semicolons.

Vector Addressing:
A vector element is addressed in MATLAB with an integer index enclosed in parentheses.

The colon notation may be used to address a block of elements,(start : increment : end), start is the
starting index, increment is the amount to add to each successive index, and end is the ending
index. A shortened format (start : end) may be used if increment is 1.

Some Useful Commands:

Matrix:
A Matrix array is two-dimensional, having both multiple rows and multiple columns, similar to
vector arrays. It begins with [, and end with ]. Spaces or commas are used to separate elements in
a row and semicolon or enter is used to separate rows.
Example:
>> f = [ 1 2 3; 4 5 6]
f=
1 2 3
4 5 6
>> h = [ 2 4 6; 1 3 5]
h=
2 4 6
1 3 5

Magic Function:
For example you can generate a matrix by entering
>> m=magic(4)
It generates a matrix whose elements are such that the sum of all elements in its rows, columns
and diagonal elements are same
Sum Function:
You can verify the above magic square by entering
>> sum(m)
For rows take the transpose and then take the sum
>> sum(m’)
Diag:
You can get the diagonal elements of a matrix by entering
>> d=diag(m)
Matrix Addressing:
matrixname(row, column)
colon may be used in place of a row or column reference to select the entire row or column.

recall:
f=
1 2 3
4 5 6

h=
2 4 6
1 3 5

Some useful commands:

More commands:
Array Operations:
 Scalar-Array Mathematics
For addition, subtraction, multiplication, and division of an array by a scalar simply apply the
operations to all elements of the array.

Example:
>> f = [ 1 2; 3 4]
f=
1 2
3 4
>> g = 2*f – 1 g =
1 3
5 7
Each element in the array f is multiplied by 2, then subtracted by 1.
 Element-by-Element Array-Array Mathematics

Each element in x is multiplied by the corresponding element in y.


Solutions to Systems of Linear Equations
Example: a system of 3 linear equations with 3 unknowns (x1, x2, x3):
3x1 + 2x2 – x3 = 10
-x1 + 3x2 + 2x3 = 5
x1 – x2 – x3 = -1
Let,

Then, the system can be described as:


Ax = b
 Solution by Matrix Inverse:
Ax = b
x = 𝐴�−1b
MATLAB:

Answer: x1 = 2, x2 = 1, x3 = 2

 Solution by Matrix Division:


The solution to the equation Ax = b can be computed using left division.
MATLAB:

Answer: x1 = 2, x2 = 1, x3 = 2
NOTE: left division: A\b → b÷A right division: x/y→ x ÷ y
Plotting:
Plotting a point:
>> plot ( variablename, ‘symbol’)
the function plot () creates a graphics window, called a Figure window, and named by default
“Figure No. 1”

Commands for axes:


Grids and Labels:

Additional commands for plotting:


EXERCISES
Exercise 1:

Use Matlab command to obtain the following


a. Extract the fourth row of the matrix generated by magic(6)
b. Show the results of ‘x’ multiply by ‘y’ and ‘y’ divides by ‘x’.
Given x = [0:0.1:1.1] and y = [10:21]

Exercise 2:

Use MATLAB commands to plot x and y.

x=pi/2:pi/10:2*pi;
y=sin(x);
Part II: Polynomials in MATLAB

Objective:
The objective of this session is to learn how to represent polynomials in MATLAB, find roots
of polynomials, create polynomials when roots are known and obtain partial fractions.
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.
Polynomial Function Summary:

Symbolic Math Toolbox contains additional specialized support for polynomial operations.
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)
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)
ans =
110
Convolution and Deconvolution:
Polynomial multiplication and division correspond to the operations convolution and
deconvolution. The functions conv and deconv implement these operations. Consider the
polynomials

and

To compute their product,


>>a = [1 2 3];
>>b = [4 5 6];
>>c = conv(a,b)

Use deconvolution to divide back out of the product:


>>[q,r] = deconv(c,a)

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)

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)

Calculate the derivative of the quotient a/b by calling polyder with two output arguments:
>>[q,d] = polyder(a,b)

q/d is the result of the operation.


EXERCISES
Exercise 1:
Consider the two polynomials

and

Using MATLAB compute


a. p(s) * q(s)
b. Roots of p(s) and q(s)
c. p(-1) and q(6)
Part III: Scripts in MATLAB
Objective:
The objective of this session is to introduce you to writing M-file.
Overview:
MATLAB is a powerful programming language as well as an interactive computational
environment. Files that contain code in the MATLAB language are called M-files. You create M-
files using a text editor, then use them as you would any other MATLAB function or command.
There are two kinds of M-files:
 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.
 Functions, which can accept input arguments and return output arguments. Internal
variables are local to the function.
If you're a new MATLAB programmer, just create the M-files that you want to try out in the current
directory. As you develop more of your own M- files, you will want to organize them into other
directories and personal toolboxes that you can add to your MATLAB search path. If you duplicate
function names, MATLAB executes the one that occurs first in the search path.
Scripts:
When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can
operate on existing data in the workspace, or they can create new data on which to operate.
Although scripts do not return output arguments, any variables that they create remain in the
workspace, to be used in subsequent computations. In addition, scripts can produce graphical
output using functions like plot. For example, create a file called ‘random.m’ that contains these
MATLAB commands:
% Create random numbers and plot these numbers
clc
clear
r = rand(1,50)
plot(r)
Typing the statement ‘random’ at command prompt causes MATLAB to execute the commands,
creating fifty random numbers and plots the result in a new window. After execution of the file is
complete, the variable ‘r’ remains in the workspace.
Experiment No. 2
LTI Systems and Representation

Objectives:
This experiment has following two objectives:

1. We will learn commands in MATLAB that would be used to represent such systems in terms of
transfer function or pole-zero gain representations.

2.We will also learn how to make preliminary analysis of such systems using plots of poles and
zeros locations as well as time response due to impulse, step and arbitrary inputs.
List of Equipment/Software:
Following equipment/software is required:
MATLAB

Deliverables:
 Observations and solutions to exercises provided at the end.
 Oral verification of results

Linear Time-Invariant Systems in MATLAB:


Control System Toolbox in MATLAB offers extensive tools to manipulate and analyze linear time-
invariant (LTI) models. It supports both continuous-and discrete-time systems. Systems can be
single-input/single-output (SISO) or multiple-input/multiple-output (MIMO).

Examples of Creating LTI Models:

Building LTI models with Control System Toolbox is straightforward. The following sections
show simple examples. Note that all LTI models, i.e. TF, ZPK and SS are also MATLAB objects.

Example of Creating Transfer Function Models:

You can create transfer function (TF) models by specifying numerator and denominator
coefficients. For example,

C/R = s / (s2+2s+1)

>>num = [1 0];
>>den = [1 2 1];
>>sys = tf(num,den)
Transfer function:

A useful trick is to create the Laplace variable, s. That way, you can specify polynomials using s
as the polynomial variable.

>>s=tf('s');
>>sys= s/(s^2 + 2*s + 1)

Transfer function:

Transfer Function From Single Differential Equation:


By considering the right hand side of differential equation as numerator and left hand side of
differential equation as denominator, the transfer function can be determined as represented below.
For example:

Suppose, M=5, fv=3, and K=1


Transfer function from Differential Equations:

Consider the following system:


Consider,
M1=15, M2=14
fv1=fv2=fv3= 1
K1=K2=K3=2
Example of Creating Zero-Pole-Gain Models:

To create zero-pole-gain (ZPK) models, you must specify each of the three components in vector
format. For example,

>>sys = zpk([0],[-1 -1],[1])

Zero/pole/gain:

produces the same transfer function built in the TF example, but the representation is now ZPK.

This example shows a more complicated ZPK model.

>>sys=zpk([1 0], [-1 -3 -.28],[.776])

Zero/pole/gain:
Plotting poles and zeros of a system:

pzmap:

Compute pole-zero map of LTI models.

Pzmap(sys)

Description:
pzmap(sys) plots the pole-zero map of the continuous- or discrete-time LTI model sys. For SISO
systems, pzmap plots the transfer function poles and zeros. The poles are plotted as x’s and the
zeros are plotted as o’s. You can use the functions sgrid or zgrid to plot lines of constant damping
ratio and natural frequency in the s- or z- plane.
Example:

Plot the poles and zeros of the continuous-time system.

Consider; C/R=H=(2s2+5s+1)/(s2+2s+3)
pzmap(sys1,sys2,…,sysN)

Description:
pzmap(sys1,sys2,…,sysN) plots the pole-zero map of several LTI models on a single figure. The
LTI models can have different numbers of inputs and outputs.

Consider; C/R=H=(2s2+5s+1)/(s2+2s+3)
C/R=L=(s+1)/(3s2+5s+7)

[p,z] = pzmap(sys)

Description:
When invoked with left-hand arguments, [p,z] = pzmap(sys) returns the system poles and zeros in
the column vectors p and z. No plot is drawn on the screen.

Simulation of Linear systems to different inputs:

impulse, step, ramp and parabolic response

You can simulate the LTI systems to inputs like impulse, step and other standard inputs and
see the plot of the response in the figure window. MATLAB command ‘impulse’ calculates
the unit impulse response of the system, ‘step’ calculates the unit step response of the system.
When invoked without left-hand arguments, all these commands plots the response on the
screen.

Impulse Response:

To obtain an impulse response


Step Response:

>>step(H)

Time-interval specification:

To contain the response of the system you can also specify the time interval to simulate the system.
For example,
Ramp and Parabolic Response:

You could get the ramp and parabolic response by dividing your transfer function by s and s2
respectively, and then taking the step response.
EXERCISES
Exercise 1:
Consider the following system:

Using MATLAB write M-file to plot the pole zero map.


Obtain the parabolic response.
Experiment No. 3
STATE VARIABLE MODELS
The purpose of this session is to introduce the students how to represent control system in time-
domain also known as state space representation.

Determine the closed loop transfer function Y(s)/R(s) = G(s)/[1+G(s)]

Determine the coefficients of N(s) and D(s)

D(s) = [0 -3 -4 ]
N(s) = [-1 -3]

Determine the closed loop transfer function using the MATLAB Commands
>> N=[-1 -3];
>> D = [0 -3 -4];
>> a=poly(N)
a=
1 4 3
>> b= poly(D)
b=
1 7 12 0
>> [num1 den1] = cloop(a,b)

num1 =
0 1 4 3
den1 =
1 8 16 3

>> tf(num1,den1)

Transfer function:
s^2 + 4 s + 3

s^3 + 8 s^2 + 16 s + 3

Transfer Function to state space conversion can be accomplished as


[A,B,C,D] = tf2ss(num,den)

>> num1 = [1 4 3];


>> den1 = [1 8 16 3];
>> [A,B,C,D] = tf2ss(num1,den1);

Where num and den are the numerator and denominator of closed loop transfer function. The

following commands will print the state-space model.

Printsys(A,B,C,D);
>> printsys(A,B,C,D)
a=
x1 x2 x3
x1 -8.00000 -16.00000 -3.00000
x2 1.00000 0 0
x3 0 1.00000 0
b=
u1
x1 1.00000
x2 0
x3 0

c=
x1 x2 x3
y1 1.00000 4.00000 3.00000

d=
u1
y1 0

Matrix A,B,C,D can be printed by entering the matrix name.


>>A

-8 -16 -3
1 0 0
0 1 0

>> B

B=

1
0
0

>> C

C=

1 4 3

>> D

D=

A system which is expressed in state-space can be converted into transfer function, by using
following commands.

[num1,den1]=ss2tf(A,B,C,D);
num1 =

0 1.0000 4.0000 3.0000

den1 =

1.0000 8.0000 16.0000 3.0000


EXERCISE

Make the M-file and find the transfer function of the following system.
Also represent it in state-space.
Experiment No. 4
Stability, Steady-State Error, Root Locus, Time-Domain Characteristics
Objective:
The objective of this lab session is to familiarize about the MATLAB commands used to find the
stability of control systems, steady state errors, and how to plot their root locus.
Stability of Control Systems:
The following MATLAB command is used to determine the stability of control systems.
>>B = isstable(sys)
B = isstable(sys) returns a logical value of 1 (true) if the dynamic system model sys has stable
dynamics, and a logical value of 0 (false) otherwise.
Example:
Determine the stability of the system shown in figure below.

Because the logical value is zero, therefore the system is unstable.


Steady-State Error:
The following MATLAB command is used to find the steady state error of the system.
>>SP=5; %input value, if you put 1 then is the same as step(sys)
>>[y,t]=step(SP*sys); %get the response of the system to a step with amplitude SP
>>sserror=abs(SP-y(end)) %get the steady state error
Example:
Find the steady state error for the above system.

Root-Locus:
The following MATLAB command is used to plot the root locus the system.
>>rlocus(sys)
rlocus(sys) calculates and plots the root locus of the open-loop SISO model sys. This function can
be applied to any of the following negative feedback loops by setting sys appropriately.
Example:
Plot the root-locus of the following system.

>>h = tf([2 5 1],[1 2 3]);


>>rlocus(h)
You can use the right-click menu for rlocus to add grid lines, zoom in or out, and invoke the
Property Editor to customize the plot. Also, click anywhere on the curve to activate a data marker
that displays the gain value, pole, damping, overshoot, and frequency at the selected point.
Time-Domain Characteristics:
The following MATLAB command is used to find the rise time, settling time, peak time, and
percent overshoot, etc.
>>S = stepinfo(sys)

S = stepinfo(sys)computes the step-response characteristics for a dynamic system model sys. The
function returns the characteristics in a structure containing the fields:

 RiseTime — Time it takes for the response to rise from 10% to 90% of the steady-state
response.

 SettlingTime — Time it takes for the error |y(t) - yfinal| between the response y(t) and the
steady-state response yfinal to fall to within 2% of yfinal.

 SettlingMin — Minimum value of y(t) once the response has risen.

 SettlingMax — Maximum value of y(t) once the response has risen.

 Overshoot — Percentage overshoot, relative to yfinal).

 Undershoot — Percentage undershoot.

 Peak — Peak absolute value of y(t)

 PeakTime — Time at which the peak value occurs.

Example:

Recall system ‘h’ again and computes all above.


Time-Domain Characteristics on Response Plot:

This example shows how to display system characteristics such as settling time and overshoot on
step response plots.
You can use similar procedures to display system characteristics on impulse response plots or
initial value response plots, such as peak response or settling time.
Create a transfer function model and plot its response to a step input at t = 0.
Example:
>>H=tf([8 18 32],[1 6 14 24]);
>>stepplot(H)
Display the peak response on the plot.
Right-click anywhere in the figure and select Characteristics > Peak Response from the menu.
A marker appears on the plot indicating the peak response. Horizontal and vertical dotted lines
indicate the time and amplitude of that response.

Click the marker to view the value of the peak response and the overshoot in a datatip.
EXERCISES

Exercise 1:

Given a unity feedback system that has forward transfer function:

Sketch the root locus using MATLAB.

Exercise 2:

For the system shown below:

Find stability, steady state error

Plot the step response

Determine all time-domain characteristics

You might also like