100% found this document useful (1 vote)
107 views18 pages

Linear Control System Lab

This lab introduces MATLAB for control systems applications. It covers defining variables, matrices and vectors, plotting functions, and writing scripts. Key MATLAB topics covered include help commands, variables, arrays, arithmetic operations, control flow, plotting, and math functions. Examples demonstrate defining scalars, vectors and matrices, array indexing and operations, plotting a polynomial using different scales, and writing scripts with if/else statements and for loops. The objectives are to introduce MATLAB concepts and provide tutorials on polynomials, scripting and programming for control systems applications.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
100% found this document useful (1 vote)
107 views18 pages

Linear Control System Lab

This lab introduces MATLAB for control systems applications. It covers defining variables, matrices and vectors, plotting functions, and writing scripts. Key MATLAB topics covered include help commands, variables, arrays, arithmetic operations, control flow, plotting, and math functions. Examples demonstrate defining scalars, vectors and matrices, array indexing and operations, plotting a polynomial using different scales, and writing scripts with if/else statements and for loops. The objectives are to introduce MATLAB concepts and provide tutorials on polynomials, scripting and programming for control systems applications.
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/ 18

Linear Control System Lab Lab 2

Utilization of MATLAB for Control system

Objectives

This lab provides an introduction to MATLAB in the first part. The lab also provides tutorial of
polynomials, script writing and programming aspect of MATLAB from control systems.

List of equipment/Software

1) MATLAB
2) Computer

Part I: Introduction to MATLAB

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, flow control etc, see how we can plot results and write simple MATLAB codes.

Getting Help from Within MATLAB

If you know the name of a function which you would like to learn how to use, use the help.

>> help functionname

This command displays a description of the function and generally also includes a list of
related Functions. If you cannot remember the name of the function, use the lookfor.

>> lookfor keyword

This command will display a list of functions that include the keyword in their
descriptions. Other help commands that you may find useful are info what and which.

MATLAB Variables — Scalars, Vectors, and Matrices

MATLAB stores variables in the form of matrices which are M x N, where M is the number of
rows and N is the number of columns. All elements of a matrix can be real or complex numbers.

Real scalar >> x=5


Complex scalar >> x = 5+10j (or >> x = 5+10i)
Row vector >> x= [123]
Column vector >> x = [1; 2; 3]
3x3matrix >> x= [1 2 3; 4 5 6; 7 8 9]

Page | 1
Linear Control System Lab Lab 2
Table 2.1: Vectors MATLAB Commands
x = start:end create row vector x starting with start, counting by one,
ending at end
x = start:increment:end create row vector x starting with start, counting by
increment, ending at or before end
linspace(start,end,number) create row vector x starting with start, ending at end, having
number elements
length(x) returns the length of vector x
y = x’ transpose of vector x

Array Indexing

In MATLAB, all arrays (vectors) are indexed starting with 1, i.e., y(1) is the first element of the
array y. Note that the arrays are indexed using parenthesis (.) and not square brackets[.] as in C/C+
+. To create an array having as elements the integers 1 through 6, just enter:

>> x=[1,2,3,4,5,6]

Alternatively, you can use the: notation,


>> x=1:6

The: notation above creates a vector starting from 1 to 6, in steps of 1. If you want to create a
vector from 1 to 6 in steps of say 2, then type:

>> x=1:2:6 = _______ 1 3 5


>> ii=2:4:17 = ________ 2 6 10 14
>> jj=20:-2:0 =____ 20 18 16 14 12 10 8 6 4 2 0

Extracting or inserting numbers in a vector can be done very easily. To concatenate an array, you
can use the [] operator, as shown in the example below:
>> x=[1:3 4 6 100:110]

To access a subset of the array, try the following:


>> x(3:7) = 3 4 6 100 101
>> length(x) = ___3____________% gives the size of the array or vector

Allocating memory

You can allocate memory for one-dimensional arrays (vectors) using the zeros command.
The following command allocates memory for a 100-dimensional array:

Page | 2
Linear Control System Lab Lab 2
>> Y=zeros(100,1);
>> Y(30) = _______0_______

Similarly, you can allocate memory for two-dimensional arrays (matrices). The command
>> Y=zeros(4,5) defines a 4 by 5 matrix.
>> Y= ones (1,5) = _______1 1 1 1 1 _____________________________

Arithmetic Operations

There are four different arithmetic operators:


+ Addition
- Subtraction
* Multiplication
/ Division (for matrices it also means inversion)
There are also three other operators that operate on an element by element basis:
.* multiplication of two vectors, element by element
./ division of two vectors, element-wise
.^ raise all the elements of a vector to a power.
Example:-

>> X= [1, 3, 4]
>> Y= [4, 5, 6]
>> X+Y = 5 8 10
>> X*Y= ERROR
>> X.*Y = 4 15 24
Table 2.2: Matrix MATLAB Commands
Transpose B = A’
Identity Matrix eye (n) returns an n x n identity matrix.
eye(m,n) returns an m x n matrix with ones on the main diagonal and
zeros elsewhere.
Addition and subtraction C = A + B, C = A – B
Scalar Multiplication B = αA, where α is a scalar.
Matrix Multiplication C = A*B
Matrix Inverse B = inv (A), A must be a square matrix in this case.
rank (A) returns the rank of the matrix A.
Matrix Powers A.^2 squares each element in the matrix
A * A computes A*A, and A must be a square matrix.
Determinant det (A), and A must be a square matrix.
Control Flow

MATLAB has the following flow control constructs:


• if statements
• switch statements
• for loops

Page | 3
Linear Control System Lab Lab 2
• while loops
• break statements
The if, for, switch and while statements need to terminate with an end statement.
IF:
>> X = -3;
>> if X>0 str =’positive’
elseif X==0 str =’equal’
elseif X <0 str = ‘negative’
else str=’error’
End
Answer :- str = ____negative___________________________
>> Do if X = 3
Answer :- str = _________positive______________________

WHILE:
>> X= -10 ;
>> while X < 0
X= X+1;
End
Value of X after execution of loop = ________0_____________________________

FOR loop:
>> X= 0;
For X= 1:10
X=X+1;
End
Value of X after execution of loop = ______10___________________________

BREAK:
The break statement lets you exit early from a for or a while loop:
>> x=-10;
while x<0
x=x+2;
if x == -2
break;
end
end
Relational Operators

Symbol Meaning:
<= Less than equal
< Less than
>= Greater than equal
> Greater than

Page | 4
Linear Control System Lab Lab 2
== Equal
~=Not equal
Complex numbers

MATLAB also supports complex numbers. The imaginary number is denoted with i or j.
>> z =3 + 4i % note that you do not need the after 4
>> conj(z) = 3 – 4i % computes the conjugate of z
>> angle(z) =____0.9273__________ % computes the phase of z
>> real(z) = ____3__________ % computes the real part of z
>> imag(z) = ____4__________ % computes the imaginary part of z
>> abs(z) = _____5_________ % computes the magnitude of z

Special characters and functions

Some common special characters used in MATLAB are:


pi >>>>>>> (3.14...)

sqrt >>>>>> indicates square root e.g., sqrt(4)=2

^ >>>>>>> indicates power(e.g., 3 2=9)

abs >>>>>> Absolute value | .| e.g., abs(-3)=3

NaN >>>>>Not-a-number, obtained when comparing mathematically undefined operations, such


as 0/0.
; >>>>>>> Indicates the end of a row in a matrix. It is also used to suppress printing on the screen
% >>>>>> Denotes a comment. Anything to the right of % is ignored by the MATLAB
interpreter and is considered as comments.

Math Functions

MATLAB comes with a large number of built-in functions that operate on matrices on an element-
by element basis. These include:
sin sine
cos cosine
tan tangent
asin inverse sine
exp exponential
log natural logarithm
log10 common logarithm
sqrt square root
abs absolute value

Page | 5
Linear Control System Lab Lab 2

Plotting

For more information on 2-D plotting, type help graph2d. Plotting a point,
>>plot (variablename, ‘symbol’)
Example:
Plotting a complex number
>> z = 1 + 0.5j;
>> plot (z, ‘.’)
Table 2.3: MATLAB Commands for Axis

Commands Description
axis ([xmin xmax ymin ymax]) Define minimum and maximum values of the axes
axis square Produce a square plot
axis equal equal scaling factors for both axes
axis normal turn off axis square, equal
axis (auto) return the axis to defaults
Plotting Curves:

 plot (x,y)- generates a linear plot of the values of x (horizontal axis) and y(vertical axis)
 semilogx (x,y)- generate a plot of the values of x and y using a logarithmic scale for x
and linear scale for y.
 semilogy (x,y)- generate a plot of the values of x and y using a linear scale on x axis and
logarithmic scale on y.
 loglog(x,y)- generate a plot of the values of x and y using logarithmic scales for both x
and y.
 plot (x, y, w, z)- multiple curves can be plotted on the same graph by using multiple
arguments in a plot command. The variables x, y, w, and z are vectors. Two curves will
be plotted: y vs. x, and z vs. w.
 subplot (m, n, p)- m by n grid of windows, with p specifying the current plot as the pth
window.

Example (Polynomial Function):

Plot the polynomial using linear/linear scale, log/linear scale, linear/log scale, & log/log scale.

Y = 2 x 2+ 7 x + 9

% Generate the polynomial:


x = linspace (0, 10, 100);
y = 2*x.^2 + 7*x + 9;
Page | 6
Linear Control System Lab Lab 2
% plotting the polynomial:
figure (1);
subplot (2,2,1), plot (x,y);
title ('Polynomial, linear/linear scale');
ylabel ('y'), grid;
subplot (2,2,2), semilogx (x,y);
title ('Polynomial, log/linear scale');
ylabel ('y'), grid;
subplot (2,2,3), semilogy (x,y);
title ('Polynomial, linear/log scale');
xlabel('x'), ylabel ('y'), grid;
subplot (2,2,4), loglog (x,y);
title ('Polynomial, log/log scale');
xlabel('x'), ylabel ('y'), grid;

Figure 2.1: Graphs of given polynomial

Adding new curves to the existing graph:


 Use the hold command to add lines/points to an existing plot.
 hold on – retain existing axes, add new curves to current axes. Axes are rescaled when
necessary.
 hold off – release the current figure window for new plots

Table 2.4: MATLAB Commands for Grids and Labels

Page | 7
Linear Control System Lab Lab 2
Command Description
grid on Adds dashed grids lines at the tick marks
grid off removes grid lines (default)
Grid toggles grid status (off to on, or on to off)
title (‘text’) labels top of plot with text in quotes
xlabel (‘text’) labels horizontal (x) axis with text is quotes
ylabel (‘text’) labels vertical (y) axis with text is quotes
text (x,y,’text’) Adds text in quotes to location (x,y) on the current
axes, where (x,y) is in units from the current plot.

Exercise 01

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]
c) Generate random matrix ‘r’ of size 4 by 5 with number varying between -8 and 9.

Page | 8
Linear Control System Lab Lab 2

Exercise 02

Use MATLAB commands to get exactly as the figure shown below


x=pi/2:pi/10:2*pi;
y=sin(x);
z=cos(x);

Figure 2.2: Plotting Signal Graph

TASK 1:

a)

magic6= magic(6);
disp('This is Magic(6): ');
disp(magic6);
This is Magic(6):
35 1 6 26 19 24

Page | 9
Linear Control System Lab Lab 2
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
4 36 29 13 18 11
fourthRowMagic6=magic6(4,:);
disp('This is the fourth Row of Magic 6: ');
disp(fourthRowMagic6);
This is the fourth Row of Magic 6:
8 28 33 17 10 15

b)

x=[0:0.1:1.1];
y=[10:21];
multip_xy= x.*y;
%y divide by x
div_yx=y./x;
%display Text
disp('x: ');
disp(x);
disp('y: ');
disp(y);
disp('Multiplication of ''x'' and ''y'' is: ');
disp(multip_xy);
disp('Division of ''y'' and ''x'' is: ');
disp(div_yx);
x:
Columns 1 through 8:

0.00000 0.10000 0.20000 0.30000 0.40000 0.50000 0.60000


0.70000

Columns 9 through 12:

0.80000 0.90000 1.00000 1.10000


y:
10 11 12 13 14 15 16 17 18 19 20 21
Multiplication of 'x' and 'y' is:
Columns 1 through 7:

Page | 10
Linear Control System Lab Lab 2

0.00000 1.10000 2.40000 3.90000 5.60000 7.50000


9.60000

Columns 8 through 12:

11.90000 14.40000 17.10000 20.00000 23.10000


Division of 'y' and 'x' is:
Columns 1 through 8:

110.000 60.000 43.333 35.000 30.000 26.667


24.286

Columns 9 through 12:

22.500 21.111 20.000 19.091

c)

r=randi([-8 9], 4,5);


disp('random 4 by 5 matrix varying between -8 and 9 ');
disp(r);
random 4 by 5 matrix varying between -8 and 9
7 -8 3 2 8
-5 7 -2 0 -2
-3 7 2 5 1
-2 5 -7 0 9

TASK2:

x=[(pi/2):(pi/10):(2*pi)];
y=sin(x);
z=cos(x);
figure;
subplot(2,1,1)
plot(x,y, 'b:+','linewidth', 2);
legend('Sine');
title('Sin Curve', 'fontsize', 10)
ylabel('sin(x)')
xlabel('Angle')

Page | 11
Linear Control System Lab Lab 2
grid;
subplot(2,1,2)
plot(x,z, 'r--*','linewidth', 2);
title('Cos Curve', 'fontsize', 10);
legend('Cosine');
ylabel('Cos(x)')
xlabel('Angle')
grid;

Part II: Polynomials in MATLAB

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.

Table2.5: Polynomial function description

Page | 12
Linear Control System Lab Lab 2
Function Description
Conv Multiply polynomials
Deconv Divide polynomials
Poly Polynomial with specified roots
Polyder Polynomial derivative
Polyfit Polynomial curve fitting
Polyval Polynomial evaluation
Polyvalm Matrix polynomial evaluation
Residue Partial-fraction expansion (residues)
Roots Find polynomial roots

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

P ( x ) =x3 −2 x −5
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

The roots function calculates the roots of a polynomial:


>>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
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

Page | 13
Linear Control System Lab Lab 2
>>polyval(p,5)
ans =
110
It is also possible to evaluate a polynomial in a matrix sense. In this case the equation becomes,
where X is a square matrix and I is the identity matrix. For example, create a square matrix X
and evaluate the polynomial p at X:
>>X = [2 4 5; -1 0 3; 7 1 5];
>>Y = polyvalm(p,X)
Y=
377 179 439
111 81 136
490 253 639

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

Partial Fraction Expansion

‘residue’ finds the partial fraction expansion of the ratio of two polynomials. This is particularly
useful for applications that represent systems in transfer function form. For polynomials b and a,

If there are no multiple roots, where r is a column vector of residues, p is a column vector of pole
locations, and k is a row vector of direct terms. Consider the transfer function

>>b = [-4 8];

Page | 14
Linear Control System Lab Lab 2
>>a = [1 6 8];
>>[r,p,k] = residue(b,a)

r=
-12
8
p=
-4
-2
k=
[]

Given three input arguments (r, p, and k), residue converts back to polynomial form:

>>[b2,a2] = residue(r,p,k)
b2 =
-4 8
a2 =
1 6 8

Exercise 01

Consider the two polynomials p ( s )=s2 +2 s +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 ).

Exercise 02

Use MATLAB command to find the partial fraction of the following


B( s) 2 s 3 +5 s 2+ 3 s+ 6
a. =
A (s) s 3+6 s 2+11 s+6
B( s) s2 +2 s +3
b. =
A (s) (s+1)3

Page | 15
Linear Control System Lab Lab 2

TASK1:
a)
p=[1 2 1];
q=[0 1 1];
product= conv(p,q);
disp('The product of p(s) and q(s) is: ');
disp(product);
The product of p(s) and q(s) is:
0 1 3 3 1
-------------------------------------------------------------------------------------------------------------------------------

b)
pRoots = roots(p);
disp('The roots of p(s) are: ');
disp(pRoots);
qRoots = roots(q);

Page | 16
Linear Control System Lab Lab 2
disp('The roots of q(s) are: ');
disp(qRoots);
The roots of p(s) are:
-1
-1
The roots of q(s) are:
-1
-----------------------------------------------------------------------------
C)
pNeg= polyval(p,-1);
disp('The evaluation of p(-1): ');
disp(pNeg);
q(6)= polyval(q,6);
disp('The evaluation of q(6): ');
disp(q(6));
The evaluation of p(-1):
0
The evaluation of q(6):
7

TASK2:
a)
b=[2 5 3 6];
a=[1 6 11 6];
[c,d,f]=residue(b,a)
c =

3.0000
-4.0000
-6.0000

d =

-1.0000
-2.0000
-3.0000

Page | 17
Linear Control System Lab Lab 2
f = 2

B)
b=[0 1 2 3];
a=[1 3 3 1];
[c,d,f]=residue(b,a)
c =

1.0000
-0.0000
2.0000

d =

-1.00000
-1.00000
-1.00000

f = []

Page | 18

You might also like