Matlab Notes
Matlab Notes
• Scripts − script files are program files with .m extension. In these files, you
write series of commands, which you want to execute together. Scripts do not
accept inputs and do not return any outputs. They operate on data in the
workspace.
Matlab comment
prompt suppress operator
assign
command
operator
output
Variables (continued …)
• View variable contents by simply typing the
variable name at the command prompt
>> a
a=
12
>>
>> a*2
a=
24
>>
7. Operators
Three types of Operator can be found in MATLAB:-
1. Arithmetic Operators
7. Operators
2. Relational Operators
8. Assignment Statement
In MATLAB the = sign is called the assignment
operator. The assignment operator assigns a value or a
computable expression to a variable in Assignment
statement.
Variable_ name = A numerical value, or a computable
expression
For e.g
>> a=12, B=4; C=(a-B)+40-a/B*10
a=
12
c=
18
9. Built in Functions
• MATLAB has a very large library of built-in functions. A
function has a name and an argument in parentheses. For
example, the function that calculates the square root of a
number is sqrt (x.)
For e.g
>> sqrt(64)
ans =
8
>> sqrt(50+14*3)
ans =
9.5917
Question
Define the variables a, b, c, and d as a =
13, b = 4.2, c = (4b) ⁄ a, d = abc/(a + b + c)
then evaluate :-
12. Scalar Vectors and Matrices
1. Scalars are like the variables and are also stored as matrix variables with 1 row and 1
column. For e.g
>> x = 3;
2. A vector can be either a row vector or a column vector
variable_name = [ type vector elements ]
– Row vector: To create a row vector type the elements with a space or a comma
between the elements inside the square brackets. For e.g
>> yr=[1984 1986 1988 1990 1992 1994 1996]
yr =
1984 1986 1988 1990 1992 1994 1996
– Column vector: To create a column vector type the left square bracket [ and then
enter the elements with a semicolon between them, or press the Enter key after
each element. Type the right square bracket ] after the last element. For e.g
>> P=[127; 130; 136]
P=
127
130
136
>> X=[2
4
5]
X=
2
4
5
12. 2 Vector
• Creating a vector with constant spacing by specifying the first term, the
spacing, and the last term.
variable_name = [m:q:n] or variable_name = m:q:n
the first term is m, the spacing is q, and the last term is n
For e.g.
>> x=[1:2:13]
x=
1 3 5 7 9 11 13
First element –3, last term 7.
If spacing is omitted, the
>> z=[-3:7]
default is 1.
z=
-3 -2 -1 0 1 2 3 4 5 6 7
• If the numbers m, q, and n are such that the value of n cannot be obtained by
adding q to m, then (for positive n) the last element in the vector will be the
last number that does not exceed n.
• If only two numbers (the first and the last terms) are typed (the spacing is
omitted), then the default for the spacing is 1.
12. 2 Vector
• Creating a vector with linear (equal) spacing by specifying the first and
last terms, and the number of terms using linspace command .
variable_name = linspace(xi,xf,n)
first element is xi , the last element is xf, Number of elements n
For e.g
>> v=linspace(0,8,6)
v=
0 1.6000 3.2000 4.8000 6.4000 8.0000
Note:
The resulting matrix must be rectangular
12.3 Matrix
(Matrix Subscripting / Indexing)
• A(:,n) Refers to the elements in all the rows of
column n of the matrix A.
• A(n,:) Refers to the elements in all the
columns of row n of the matrix A.
• A(:,m:n) Refers to the elements in all the
rows between columns m and n of the matrix A.
• A(m:n,:) Refers to the elements in all the
columns between rows m and n of the matrix A.
• A(m:n,p:q) Refers to the elements in rows m
through n and columns p through q of the matrix
A.
12.3 Matrix
(Matrix Subscripting /
Indexing)
1 2 3 4 5
A= 4
1
10
6
1
11
6
16
2
21
1
2
2 8 1.2 7 9 12 4 17
25 22
A(1:5,5) A(1:end,end)
3 7.2 3 5 8
7 13 1 18
11 23 A(:,5) A(:,end)
A(21:25) A(21:end)’
A(3,1) 4 0 4
0.5 9 4 14 5 19
56 24
A(3) 5
5 23 83 10 1315 0 20
10 25
A(4:5,2:3)
A([9 14;10 15])
The : operator
• VERY important operator in Matlab
• Means ‘to’
>> 1:10
ans =
1 2 3 4 5 6 7 8 9 10
>> 1:2:10
ans = Try the following
1 3 5 7 9 >> x=0:pi/12:2*pi;
>> y=sin(x)
The : operator and matrices
>>A(3,2:3) A=
3 2 1
ans = 5 1 0
2 1 7
1 7
>>A(:,2)
ans =
2
1
What’ll happen if you type A(:,:) ?
1
A=
Manipulating Matrices 3
5
2
1
1
0
2 1 7
Create matrices A and B and try out the the matrix operators in this slide
12.3 Matrix
(Deleting Rows and Columns)
>> A = 1:10;
>> B = reshape(A,[5,2])
B=
1 6
2 7
3 8
4 9
5 10
12.3 Matrix
(Matrix Manipulation Functions)
• zeros: Create an array of all zeros
• ones: Create an array of all ones
• eye: Identity Matrix
• rand: Uniformly distributed random numbers
• diag: Diagonal matrices and diagonal of a matrix
• size: Return array dimensions
• fliplr: Flip matrices left-right
• flipud: Flip matrices up and down
• repmat: Replicate a matrix
12.3 Matrix
(Matrix Manipulation Functions)
• transpose (’): Transpose matrix
• rot90: rotate matrix 90
• tril: Lower triangular part of a matrix
• triu: Upper triangular part of a matrix
• cross: Vector cross product
• dot: Vector dot product
• det: Matrix determinant
• inv: Matrix inverse
• eig: Evaluate eigenvalues and eigenvectors
• rank: Rank of matrix
15 MATLAB Graphics
1. 2-D plots
2. 3-D plots
15.1 2-D Plots
• The plot command is used to create two dimensional plots. The
simplest form of the command is:
plot(x,y)
>> x=[1 2 3 5 7 7.5 8 10];
>> y=[2 6.5 7 7 5.5 4 6 8];
>> plot(x,y)
plot(x,y,‘linespecifiers’,‘PropertyName’,PropertyValue)
x and y are each a vector (one-dimensional array).
15.1 2-D Plots
(Line Specifiers)
•plot(x,y) A blue solid line connects
the points with no markers (default).
plot(x,y,‘-b’,u,v,‘--r’,t,h,‘g:’)
plots y vs. x with a solid blue line, v vs.u with a
dashed red line, and h vs. t with a dotted green line.
15.1 2-D Plots
(PLOTTING MULTIPLE GRAPHS IN THE
SAME PLOT)
• Using the hold on and hold off Commands
For e.g.
x=[-2:0.01:4];
y=3*x.^3-26*x+6;
yd=9*x.^2-26;
ydd=18*x;
plot(x,y,'-b') The first graph is created
hold on
plot(x,yd,'--r') Two more graphs are added to the figure
plot(x,ydd,':k')
hold off
15.1 2-D Plots
(PLOTTING MULTIPLE GRAPHS IN THE SAME
PLOT)
• Using the line Command.
• With the line command additional graphs (lines) can be
added to a plot that already exists. The form of the line
command is:
line(x,y,‘PropertyName’,PropertyValue)
For e.g
x=[-2:0.01:4];
y=3*x.^3-26*x+6;
yd=9*x.^2-26;
ydd=18*x;
plot(x,y,'LineStyle','-','color','b')
line(x,yd,'LineStyle','--','color','r')
line(x,ydd,'linestyle',':','color','k')
15.1 2-D Plots
(Formatting a Plot)
• Labels can be placed next to the axes with the xlabel and ylabel
command which have the form
xlabel(‘text as string’)
ylabel(‘text as string’
• A title can be added to the plot with the title command
title(‘text as string’)
• A text label can be placed in the plot with the text or gtext commands
text(x,y,‘text as string’)
gtext(‘text as string’)
• The legend command places a legend on the plot.
legend(‘string1’,‘string2’, ..... ,pos)
– pos = -1 Places the legend outside the axes boundaries on the right side.
– pos = 0 Places the legend inside the axes boundaries in a location that interferes
the least with the graphs.
– pos = 1 Places the legend at the upper-right corner of the plot (default).
– pos = 2 Places the legend at the upper-left corner of the plot.
– pos = 3 Places the legend at the lower-left corner of the plot.
– pos = 4 Places the legend at the lower-right corner of the plot.
15.1 2-D Plots
(Formatting a Plot)
• The axis command can be used to change the
range and the appearance of the axes.
• A mesh or surface
plot is created with
the mesh or surf
command, which has
the form:
mesh(X,Y,Z)
surf(X,Y,Z)
15.2 3-D Plots(MESH AND SURFACE PLOTS)
15.2 3-D Plots(MESH AND SURFACE PLOTS)
15.2 3-D Plots(MESH AND SURFACE PLOTS)
15.2 3-D Plots(SPECIAL GRAPHICS)
15.2 3-D Plots(SPECIAL GRAPHICS)
15.2 3-D Plots(SPECIAL GRAPHICS)
Unit 2
MATLAB Programing, Control structures,
Functions subprograms, types of functions, error
and warnings, MATLAB debugger, polynomials,
solution of simultaneous linear and non linear
equations, curve fitting data analysis,
differentiation, integration.
16 Input and Output
OutPut as Assignment
19 M files
Types of M files
1. Scripts
2. Functions
19.1 Script file
• A script file is a sequence of MATLAB commands, also called a
program.
• When a script file runs (is executed), MATLAB executes the
commands in the order they are written just as if they were
typed in the Command Window.
• When a script file has a command that generates an output
(e.g., assignment of a value to a variable without a semicolon
at the end), the output is displayed in the Command Window.
• Using a script file is convenient because it can be edited
(corrected or otherwise changed) and executed many times.
• Script files can be typed and edited in any text editor and then
pasted into the MATLAB editor.
• Scripts will manipulate and
Scripts (continued)
store variables and matrices
in the Matlab Workspace
(memory).
• They can be called from the
Matlab command line by Will be slightly
typing the (case sensitive!) different in Linux
filename of the script file.
>> myscript
• Scripts can be opened in
the editor by the following
>> open myscript
73
19.1 Script file
• From the menu choose File then
New then M-file or script file. Or
1. >> edit Estatistic.m
2. Write into the editor:
x = [4 3 2 10 -1];
3. Save the file n = length(x);
sum1 = 0; sum2 = 0;
for i=1:n
sum1 = sum1 + x(i);
>> run Estatistic sum2 = sum2 + x(i)*x(i);
end
>> avg, std avg = sum1/n;
std= sqrt(sum2/n – avg * avg);
• avg = 3.6000
• std = 3.6111
Functions
• Programming in Matlab.
• Users can write functions which can be called from the command line.
• Functions can accept input variable(s)/matrice(s) and will output
variable(s)/matrice(s).
• Functions will not manipulate variable(s)/matrice(s) in the Matlab
Workspace.
• In Matlab functions closely resemble scripts and can be written in the
Matlab editor. Matlab functions have the function keyword.
• Remember that the filename of a function will be its calling function
name.
• Don’t overload any built-in functions by using the same filename for
your functions or scripts!
• Functions can be opened for editing using the open command. Many
built-in Matlab functions can also be viewed using this command.
75
19.2 Function file
• With parameters and returning values
• Only visible variables defined inside the function or parameters
• Usually one file for each function defined
Structure:
function [out1, out2, ..., outN] = name-function (par1, par2, ..., parM)
sentence;
….
sentence;
end
Functions (continued)
>> I=iterate(5) function name input
output
I=
1 4 9 16 25
function keyword
77
Functions (continued)
Functions can have many
>> [i j]=sort2(2,4) outputs contained in a matrix
i=
4
j=
2
if statement
>> block
78
19.2 Function file
function [avg,std] = Fstatistic (x)
1) >> edit n = length(x);
Fstatistic.m [sum1,sum2] = sum(x,n);
avg = sum1/n;
2) Write into the editor: std = sqrt(sum2/n – avg*avg);
3) Save the file end
p = 3.6000
d = 3.6111
p = 3.6000
d = 3.6111
The H1 line.
Help text
Function body
(computer program).
Assignment of values to
output arguments.
LOCAL AND GLOBAL VARIABLES
• All the variables in a function file are local (the input and
output arguments and any variables that are assigned
values within the function file).
function a = fcn1()
global b
b = 6;
function a = fcn1() a = 5+b;
a = 5;
b = 6; fcn2()
fcn2() end
end
function a = fcn2() function a = fcn2()
a = b; global b
end a = b;
end
19.2 Function file
Write a user-defined function (name it FtoC) that converts temperature in degrees
F to temperature in degrees C. Use the function to solve the following problem.
The change in the length of an object,ΔL , due to a change in the temperature, ΔT ,
is given by: ΔL= αLΔT , where α is the coefficient of thermal expansion. Determine
the change in the area of a rectangular (4.5 m by 2.25 m) aluminum
(α=23.10−6 1/ ͦ C) plate if the temperature changes from 40 F to 92 F.
function C=FtoC(F)
%FtoC converts degrees F to degrees C
C=5*(F-32)./9;
Structure:
function [out1, out2, ..., outN] = name-function (par1, par2, ..., parM)
sentence;
….
sentence;
end
19.2 Function file
function [avg,std1] = Fstatistic1 (x)
x
1) >> edit n = length(x)
Fstatistic1.m sum1 = sum(x)
avg = sum1/n
2) Write into the editor: std1 = sqrt(mean((x-avg).^2))
3) Save the file end
p = 3.6000
d = 3.6111
For E.g
>> FA=inline('exp(x.^2)./sqrt(x.^2+5)')
FA =
Inline function:
FA(x) = exp(x.^2)./sqrt(x.^2+5)
>> FA(2)
ans =
18.1994
>> FA([1 0.5 2])
ans =
1.1097 0.5604 18.1994
17 LOOPS
S.No. Loop Type Description
1) while loop Repeats a statement or group of statements while a
given condition is true. It tests the condition before
executing the loop body.
2) for loop Executes a sequence of statements multiple times
and abbreviates the code that manages the loop
variable.
3) nested loops You can use one or more loops inside any another
loop.
17.1 For Loop
>>for k=1:3:10
for index = values x = k^2
end
<program
>> x =
statements> 1
... x =
16
end x =
49
x =
100
17.2 While Loop
While <expression>
<statements>
end
>> x =
1
>> x=1
x =
while x<=15
2
x=2*x
x =
end
4
x =
8
x =
16
17.2 While Loop
While statement block
Without ; to
print output
i=
4
i=
16
i=
256
94
17.2 While Loop
Use a while loop to calculate factorial(10).
n = 10;
f = n;
while n > 1
n = n-1;
f = f*n;
end
disp(['n! = ' num2str(f)])
n! = 3628800
17.3 NESTED LOOPS
Create a Hilbert matrix of order 10.
s = 10;
H = zeros(s);
for c = 1:s
for r = 1:s
H(r,c) = 1/(r+c-1);
end
end
17.3 NESTED LOOPS
for m = 1:j
for n = 1:k
<statements>;
end
end
for i=2:100
for j=2:100
if(~mod(i,j))
break % if factor found, not prime
end
end
if(j > (i/j))
fprintf('%d is prime\n', i);
end
end
1. Write a MATLAB program to determine the total number of elements (element which is
less then 0.25) of a randomly distributed matrix A(10000,20000).
2 & 3. Write the outputs of the following programs in correct order.
m=0;
while m<110
function a = fcn1() i=1;
global b k=0;
b = 6; while i<5
a = 5+b; j=1;
fprintf('DRG %d\n', i+m);
fcn2() while j<20
end fprintf('%d\n', 7+j+k+m);
function a = fcn2() j=j+7;
global b end
a = b; i=i+1;
end k=k+20;
end
m=m+98;
end
4. Write two anonymous functions which are defined as cross section area of a cylinder
and volume of a cylinder respectively. There are three different cylinders having different
cross-section areas and lengths. Each Cylinder is filled with different type of liquid.
Weights of liquid in cylinder 1,2 and 3 are m1, m2 and m3 respectively. Write a function
or script to calculate the density of liquids in each cylinder using aforementioned
anonymous functions.
1. Write a MATLAB program to determine the total number of elements (element which is
less then 0.25) of a randomly distributed matrix A(10000,20000).
A=rand(10,20);
A=rand(10,20)
b=find(A<0.25);
c=0;
c=length(b)
for(i=1:10)
for(j=1:20)
if A(i,j)<0.25
c=c+1
end
end A=rand(10,20);
end b=A<0.25;
c=sum(b)
d=sum(c)
2 . Write the outputs of the following programs in correct order.
function a = fcn1()
global b
b = 6;
a = 5+b;
fcn2() Ans=6
end Ans =11
function a = fcn2()
global b
a = b;
end
19.2 Function file
• With parameters and returning values
• Only visible variables defined inside the function or parameters
• Usually one file for each function defined
Structure:
function [out1, out2, ..., outN] = name-function (par1, par2, ..., parM)
sentence;
….
sentence;
end
function
function y=simple(x)
y=(x.^4.*sqrt(3*x+5))./(x.^2+1).^2
>> simple(6)
ans =
4.5401
>> F=simple(6)
F=
4.5401
>> F=simple([2 4 6 8])
y=
2.1226 3.6523 4.5401 5.2207
F=
2.1226 3.6523 4.5401 5.2207
>> x=[2 4 6 9]
x=
2 4 6 9
>> F=simple(x)
y=
2.1226 3.6523 4.5401 5.5197
F=
2.1226 3.6523 4.5401 5.5197
19.2 Function file
function [avg,std1] = Fstatistic1 (x)
x
1) >> edit n = length(x)
Fstatistic1.m sum1 = sum(x)
avg = sum1/n
2) Write into the editor: std1 = sqrt(mean((x-avg).^2))
3) Save the file end
p = 3.6000
d = 3.6111
r1=10;l1=10;m1=10;r2=12;l2=13 function[d1,d2,d3]=density2(r1,
;m2=12;r3=20;l3=20;m3=20; l1,m1,r2,l2,m2,r3,l3,m3)
volume=@(r,l)(pi*r*r*l); r1=10;l1=10;m1=10;r2=12;l2=13;m
area=@(r)(pi*r); 2=12;r3=20;l3=20;m3=20;
d1=m1/volume(r1,l1) volume=@(r,l)(pi*r*r*l);
d2=m2/volume(r2,l2) area=@(r)(pi*r*r);
d3=m3/volume(r3,l3) d1=m1/volume(r1,l1)
d2=m2/volume(r2,l2)
d3=m3/volume(r3,l3)
end
function[d]=density3(r,l,m)
volume=@(r,l)(pi*r.*r.*l); r = [10 15 20];
area=@(r)(pi*r); l = [10 15 20];
d=m./volume(r,l); m = [10 14 20];
end [d]=density3 (r,l,m)
Function functions
Passing a user-defined function into a function function:
function xyout=funplot(Fun,a,b)
% funplot makes a plot of the function Fun which is passed in
x=linspace(a,b,100);
y=Fun(x);
xyout(1,1)=a; xyout(2,1)=(a+b)/2; xyout(3,1)=b;
xyout(1,2)=y(1); xyout(2,2)=Fun((a+b)/2); xyout(3,2)=y(100);
plot(x,y)
xlabel('x'), ylabel('y')
function y=Fdemo(x)
y=exp(-0.17*x).*x.^3-2*x.^2+0.8*x-3;
>> ydemo=funplot(@Fdemo,0.5,4)
ydemo =
0.5000 -2.9852
2.2500 -3.5548
4.0000 0.6235
Function
function xyout=funplot1(a,b)
% funplot makes a plot of the function Fun which is passed in
x=linspace(a,b,100);
y=exp(-0.17*x).*x.^3-2*x.^2+0.8*x-3;
xyout(1,1)=a; xyout(2,1)=(a+b)/2; xyout(3,1)=b;
xyout(1,2)=y(1); xyout(2,2)=y((a+b)/2);
xyout(3,2)=y(100);
plot(x,y)
xlabel('x'), ylabel('y')
>> xyout=funplot1(0.5,4)
xyout =
0.5000 -2.9852
2.2500 -3.5694
4.0000 0.6235
Function functions
Passing an anonymous function into a function function:
function xyout=funplot(Fun,a,b)
% funplot makes a plot of the function Fun which is passed in
x=linspace(a,b,100);
y=Fun(x);
xyout(1,1)=a; xyout(2,1)=(a+b)/2; xyout(3,1)=b;
xyout(1,2)=y(1); xyout(2,2)=Fun((a+b)/2); xyout(3,2)=y(100);
plot(x,y)
xlabel('x'), ylabel('y')
>> FdN=@(x) exp(-0.17*x).*x.^3-2*x.^2+0.8*x-3
>> ydemo=funplot(FDN,0.5,4)
ydemo =
0.5000 -2.9852
2.2500 -3.5548
4.0000 0.6235
Function
function xyout=funplot2(a,b)
% funplot makes a plot of the function Fun which is passed in
x=linspace(a,b,100);
FDN=@ (x) exp(-0.17*x).*x.^3-2*x.^2+0.8*x-3;
xyout(1,1)=a; xyout(2,1)=(a+b)/2; xyout(3,1)=b;
xyout(1,2)=FDN(a);
xyout(2,2)=FDN((a+b)/2); xyout(3,2)=FDN(b);
plot(x,FDN)
xlabel('x'), ylabel('y')
>> xyout=funplot2(0.5,4)
xyout =
0.5000 -2.9852
2.2500 -3.5694
4.0000 0.6235
Function functions
Passing a user-defined function into a function function:
function xyout=funplotS(Fun,a,b)
x=linspace(a,b,100);
y=feval(Fun,x);
xyout(1,1)=a; xyout(2,1)=(a+b)/2; xyout(3,1)=b;
xyout(1,2)=y(1);
xyout(2,2)=feval(Fun,(a+b)/2); xyout(3,2)=y(100);
plot(x,y)
xlabel('x'), ylabel('y')
function y=Fdemo(x)
y=exp(-0.17*x).*x.^3-2*x.^2+0.8*x-3;
>> ydemoS=funplotS('Fdemo',0.5,4)
ydemoS =
0.5000 -2.9852
2.2500 -3.5548
4.0000 0.6235
sub functions
function [me SD] = stat(v)
n=length(v);
me=AVG(v,n);
SD=StandDiv(v,me,n);
function av=AVG(x,num)
av=sum(x)/num;
function
Sdiv=StandDiv(x,xAve,num)
xdif=x-xAve;
xdif2=xdif.^2;
Sdiv= sqrt(sum(xdif2)/(num-1));
AveGrade =
76.8182
StanDeviation =
13.6661
NESTED FUNCTIONS
function [me SD]=statNest(v)
n=length(v);
me=AVG(v);
function av=AVG(x)
av=sum(x)/n;
end
function Sdiv=StandDiv(x)
xdif=x-me;
xdif2=xdif.^2;
Sdiv= sqrt(sum(xdif2)/(n-1));
end
SD=StandDiv(v);
end
AveGrade =
76.8182
StanDeviation =
13.6661
19 POLYNOMIALS
Polynomial MATLAB representation
• 8x + 5 •p = [8 5]
• 2x2 – 4x + 10 •d = [2 –4 10]
• 6x2 – 150 •h = [6 0 –150]
• 5x5 + 6x2 – 7x
•c = [5 0 0 6 –7 0]
19 POLYNOMIALS
• The value of a polynomial at Q:- f(x) = x5 – 12.1x4 + 40.59x3 – 17.015x2 –
71.95x + 35.88
a point x can be calculated a) Calculate f(9)
with the function polyval b) Plot the polynomial for –1.5 ≤ x ≤ 6.7
which has the form: >> p = [1 -12.1 40.59 -17.015 -
polyval(p,x) 71.95 35.88];
>> polyval(p,9)
ans =
• p is a vector with the 7.2611e+003
coefficients of the
>> x=-1.5:0.1:6.7;
polynomial. >> y=polyval(p,x);
• x is a number, or a variable >> plot(x,y)
that has an assigned value,
or a computable expression.
19 POLYNOMIALS
• Roots of a Polynomial:- When the roots of a
polynomial are known, the
MATLAB has a function, poly command can be used for
called roots, that determining the coefficients of
determines the root, or the polynomial. The form of
roots, of a polynomial. the poly command is:
The form of the function
is: p = poly(r)
r = roots(p)
• r is a row or column
• r is a column vector with vector with the roots of
the roots of the the polynomial
polynomial
• p is a row vector with the • p is a row vector with
coefficients of the the coefficients of the
polynomial. polynomial.
19 POLYNOMIALS
• Addition and Subtraction : Two polynomials can
be added (or subtracted) by adding (subtracting)
the vectors of the coefficients.
For e.g
[q,r] = deconv(u,v)
c = conv(a,b)
•q is a vector with the coefficients of the
• c is a vector of the coefficients quotient polynomial.
of the polynomial that is the •r is a vector with the coefficients of the
product of the multiplication. remainder polynomial.
• a and b are the vectors of the •u is a vector with the coefficients of the
coefficients of the
polynomials that are being numerator polynomial.
multiplied. •v is a vector with the coefficients of the
denominator polynomial.
19 POLYNOMIALS
multiplication of the above polynomials
>> p1=[3 15 0 -10 -3 15 -40];
>> p2=[3 0 -2 -6];
>> pm=conv(p1,p2)
pm =
9 45 -6 -78 -99 65 -54 -12 -10 240
19 POLYNOMIALS
Derivatives of Polynomials
For e.g
>> p = [3 0 -4 10 -25];
>> q = polyint(p)
q =
0.6000 0 -1.3333 5.0000 -25.0000 0
21 Curve Fitting
• Curve fitting with polynomials e.g:-
is done in MATLAB with the x=[0.9 1.5 3 4 6 8 9.5];
polyfit function, which uses
the least squares method. y=[0.9 1.5 2.5 5.1 4.5 4.9 6.3];
p = polyfit(x,y,n) p=polyfit(x,y,3)
p =
p is the vector of the coefficients 0.0220 -0.4005 2.6138 -1.4158
of the polynomial that fits the xp=0.9:0.1:9.5;
data.
yp=polyval(p,xp);
x is a vector with the horizontal plot(x,y,'o',xp,yp)
coordinates of the data points xlabel('x'); ylabel('y')
(independent variable).
t=0:0.5:5;
w=[6 4.83 3.7 3.15 2.41 1.83 1.49 1.21 0.96 0.73 0.64];
p=polyfit(t,log(w),1);
m=p(1)
b=exp(p(2))
tm=0:0.1:5;
wm=b*exp(m*tm);
plot(t,w,'o',tm,wm)
22 Interpolation
One-dimensional interpolation in MATLAB is done with the interp1 (the last character is
the number one) function, which has the form:
yi = interp1(x,y,xi,‘method’)
x=0:1.0:5;
y=[1.0 -0.6242 -1.4707 3.2406 -0.7366 -6.3717];
xi=0:0.1:5;
yilin=interp1(x,y,xi,'linear');
yispl=interp1(x,y,xi,'spline');
yipch=interp1(x,y,xi,'pchip');
yfun=1.5.^xi.*cos(2*xi);
subplot(1,3,1)
plot(x,y,'o',xi,yfun,xi,yilin,'--');
subplot(1,3,2)
plot(x,y,'o',xi,yfun,xi,yispl,'--');
subplot(1,3,3)
plot(x,y,'o',xi,yfun,xi,yipch,'--');
Question
x -2 -1 0 1 2
y -39 -15 -5 -3 39
– There are five sets of (x,y) above, polyfit can give the 4th order
polynomial form by Lagrange interpolation. To compare, we
can use interp1 to give the more smooth fitting curve by
piecewise cubic Hermite interpolation.
Question
The M-file : L_interperlation.m
x=[-2 -1 0 1 2];
y=[-9 -15 -5 -3 39];
p=polyfit(x,y,4)
x1=linspace(-2,2,50);
y1=polyval(p,x1);
y2=interp1(x,y,x1,'pchip');
plot(x,y,'o',x1,y1,'-',x1,y2,'.');
xlabel('x'),ylabel('y=f(x)')
>> L_interpolation
p =
3.0000 2.0000 -7.0000 4.0000 -5.0000
f ( x) 3 x 2 x 7 x 4 x 5
4 3 2
23 Multiple linear regression
Multiple linear regression
b = regress(y,X)
[b,bint] = regress(y,X)
[b,bint,r] = regress(y,X)
0.1979
0.0625
bint = r=
-0.0404
0.0910 0.3048
0.0308
-0.0775 0.2025
0.0446
-0.0179
0.0096
-0.0267
23 Multiple linear regression
y=b1*x+b2*x1+b3
0.1018
0.4844 c =
-0.2847
>> [a,b,c]=regress(y,X)
-0.0003
a = 0.0014
0.0014
0.1018 -0.0032
0.4844 -0.0031
-0.2847
0.0038
23 Multiple linear regression
Using ‘\’ command
Taking Previous Example
ans =
0.1018
0.4844
-0.2847
Question
X = [1920 1700 1090 990 1030 995 930]
Y= [1.04 0.78 0.62 0.58 0.57 0.58 0.62]*1000000
Use polyfit ‘\’ and regress to find ‘a’ and ‘b’
Y=aX+b
SOLVING AN EQUATION WITH ONE VARIABLE
x = fzero(function,x0)
• x is the solution, which is a scalar.
• function is the function to be solved. It can be entered in
several different ways:
1. The simplest way is to enter the mathematical expression
as a string.
2. The function is created as a user-defined function in a
function file and then the function handle is entered
3. The function is created as an anonymous function and then
the name of the anonymous function
SOLVING AN EQUATION WITH ONE VARIABLE
Problem: Determine the solution of the equation (𝑥𝑒 −𝑥 = 0.2).
Sol: 𝑓 𝑥 = 𝑥𝑒 −𝑥 −0.2=0
>> fplot('x*exp(-x)-0.2',[0 8])
>> x1=fzero('x*exp(-x)-0.2',0.7)
x1 =0.2592
>> F=@(x)x*exp(-x)-0.2
>> fzero(F,2.8)
ans =2.5426
>> fzero(F,0)
x1 =0.2592
>> fzero(F,8)
ans =2.5426
FINDING A MINIMUM OR A MAXIMUM OF A FUNCTION
x = fminbnd(function,x1,x2)
>> q=quad(@Fdemo,0.5,4)
q= -9.4121
If you have data sheet i.e. x, y data you can also use trapezoidal method
q = trapz(x,y)
Function functions
Passing a user-defined function into a function function:
function xyout=funplot(Fun,a,b)
% funplot makes a plot of the function Fun which is passed in
x=linspace(a,b,100);
y=Fun(x);
xyout(1,1)=a; xyout(2,1)=(a+b)/2; xyout(3,1)=b;
xyout(1,2)=y(1); xyout(2,2)=Fun((a+b)/2); xyout(3,2)=y(100);
plot(x,y)
xlabel('x'), ylabel('y')
function y=Fdemo(x)
y=exp(-0.17*x).*x.^3-2*x.^2+0.8*x-3;
>> ydemo=funplot(@Fdemo,0.5,4)
ydemo =
0.5000 -2.9852
2.2500 -3.5548
4.0000 0.6235
x=0:0.5:4;
y=[1.8 2.7 3.5 4.7 5.2 6.1 6.9 7.8 9.0];
p=polyfit(log(x),log(y),1); %%% y=b*x^m
m=p(1);
b=exp(p(2));
xf=0:0.1:4;
yf=b*(xf.^m);
ylin=interp1(x,y,xf,'linear');
yspl=interp1(x,y,xf,'spline');
ypch=interp1(x,y,xf,'pchip');
subplot(1,3,1)
plot(x,y,'o',xf,yf,xf,ylin,'.')
subplot(1,3,2)
plot(x,y,'o',xf,yf,xf,yspl,'.')
subplot(1,3,3)
plot(x,y,'o',xf,yf,xf,ypch,'.')
sub functions
function [me SD] = sdav(v)
n=length(v);
me=AVG(v,n);
SD=StandDiv(v,me,n);
function av=AVG(x,n)
av=sum(x)/n;
function Sdiv=StandDiv(x,av,n)
xdif=x-av;
xdif2=xdif.^2;
Sdiv= sqrt(sum(xdif2)/(n-1)); x=[3.0 3.2 4.5 2.1 4.1 3.0 4.3
4.1 2.1 4.1];
y=[3.3 3.2 4.5 2.1 4.5 3.0 4.8
4.1 2.1 4.1];
z=[3.3 3.2 4.5 2.1 4.5 3.0 4.8
4.1 2.1 4.1];
[m1,s1]= sdav(x)
[m2,s2]= sdav(y)
[m3,s2]= sdav(z)
p=[2000, 2005, 2010]
mean=[m1, m2, m3]
bar(p, mean)
function S = entropy (fun, m, r, l, a,b)
x=linspace(a,b,100);
g=fun(x);
vol=@(r,l)(2*pi*r*r*l);
R= 2*pi*(m/(vol(r,l)))*((g.*log(g)- g +1).*x.^2)
S=sum(R);
end
object_name = sym(‘string’)
>> a=sym('a')
a=
a
>> g=sym('gamma')
g=
gamma
>> c=sym(5)
c=
5
>> syms y z d
23 Symbolic Math
Symbolic variables
Use syms to define symbolic variables. (Or use sym to create
an abbreviated symbol name.)
>> syms m n b c x
>> th = sym('theta')
>> sin(th)
ans = sin(theta)
>> sin(th)^2 + cos(th)^2
ans = cos(theta)^2 + sin(theta)^2
>> y = m*x + b
y = b + m*x
23 Symbolic Math
Symbolic Objects
Use sym to create a symbolic number, and double to convert
to a normal number.
>> sqrt(2)
ans = 1.4142
>> v = sqrt(sym(2))
v = 2^(1/2)
>> double(var)
ans = 1.4142
>> h=2*a/3+4*a/7-6.5*x+x/3+4*5/3-1.5
h=
(26*a)/21 - (37*x)/6 + 31/6
>> syms m x b
>> y = m*x + b → y = b + m*x
>> subs(y,x,3) → ans = b + 3*m
>> subs(y, [m b], [2 3]) → ans = 2*x + 3
>> subs(y, [b m x], [3 2 4])→ ans = 11
23 Symbolic Math
Substitutions
Variables can hold symbolic expressions.
>> syms th z
>> f = cos(th) → f = cos(th)
>> subs(f,pi) → ans = -1
>> syms x h w y d t
>> S=h*x^2+d*y^2+t*w^2
S=
t*w^2 + h*x^2 + d*y^2
>> findsym(S)
ans =
d, h, t, w, x, y
>> findsym(S,5)
ans =
x,y,w,t,h
23 Symbolic Math
Manipulating symbolic expressions
• expand()
• factor()
• collect()
• simplify()
• simple()
• poly2sym()
23 Symbolic Math
Manipulating symbolic expressions
Expand()
>> syms a x y
>> S=(x+5)*(x-a)*(x+4)
S=
-(a-x)*(x+4)*(x+5)
>> T=expand(S)
T=
20*x-20*a-9*a*x-a*x^2+9*x^2+x^3
>> expand(sin(x-y))
ans =
cos(y)*sin(x)-cos(x)*sin(y)
23 Symbolic Math
Manipulating symbolic expressions
collect(S) collect(S, variable_name)
>> syms x y >> T=(2*x^2+y^2)*(x+y^2+3)
>> S=(x^2+x-exp(x))*(x+3) T=
S= (2*x^2+y^2)*(y^2+x+3)
(x + 3)*(x - exp(x) + x^2) >> G=collect(T)
>> F = collect(S) G=
F= 2*x^3+(2*y^2+6)*x^2+y^2*x+y^2
x^3+4*x^2+(3-exp(x))*x-3*exp(x) *(y^2+3)
>> H=collect(T,y)
H=
y^4+(2*x^2+x+3)*y^2+2*x^2*(x+
3)
23 Symbolic Math
Manipulating symbolic expressions
Factor()
>> syms x
>> S=x^3+4*x^2-11*x-30
S=
x^3+4*x^2-11*x-30
>> factor(S)
ans =
(x+5)*(x-3)*(x+2)
23 Symbolic Math
Manipulating symbolic expressions
simple(S)
>> syms x
>> S=(x^3-4*x^2+16*x)/(x^3+64)
S=
(x^3-4*x^2+16*x)/(x^3+64)
>> F = simple(S)
F=
x/(x+4)
23 Symbolic Math
Manipulating symbolic expressions
pretty(S)
>> syms a b c x
>> S=sqrt(a*x^2 + b*x + c)
S=
(a*x^2+b*x+c)^(1/2)
>> pretty(S)
1
2 2
(a𝑥 + b x + c)
23 Symbolic Math
Solving algebraic equations
h = solve(eq) or h = solve(eq,var)
>> syms a b c d x
>> solve('a*x^2 + b*x + c = 0')
→ ans = % Quadratic equation!
-(b + (b^2 - 4*a*c)^(1/2))/(2*a)
-(b - (b^2 - 4*a*c)^(1/2))/(2*a)
>> solve('a*x^3 + b*x^2 + c*x + d = 0')
→ Nasty-looking expression
>> solve('cos(2*y)+3*sin(y)=2')
ans =
pi/2
pi/6
(5*pi)/6
23 Symbolic Math
Solving algebraic equations (Using Matrix)
23 Symbolic Math
Solving systems of equations
output = solve(eq1,eq2,....,eqn) or
output = solve(eq1,eq2,...,eqn,var1,var2,...,varn)
Systems of equations can be solved.
y=
12/41
z=
108/41
23 Symbolic Math
Solving systems of equations
output = solve(eq1,eq2,....,eqn) or
output = solve(eq1,eq2,...,eqn,var1,var2,...,varn)
Systems of nonlinear equations can be solved.
>> [x, y] = solve('x^2 + x*y + y = 3', ...
'x^2 - 4*x + 3 = 0')
→ Two solutions: x = [ 1 ; 3 ]
y = [ 1 ; -3/2 ]
>> syms x y t
>> S=10*x+12*y+16*t;
>> [xt yt]=solve(S, '5*x-y=13*t')
xt = 2*t
yt = -3*t
>> syms x y R
>> [xc,yc]=solve('(x-2)^2+(y-4)^2=R^2','y=x/2+1')
xc =
((4*R^2)/5 - 64/25)^(1/2) + 14/5
14/5 - ((4*R^2)/5 - 64/25)^(1/2)
yc =
((4*R^2)/5 - 64/25)^(1/2)/2 + 12/5
12/5 - ((4*R^2)/5 - 64/25)^(1/2)/2
23 Symbolic Math
Solving algebraic equations
>> syms x y
>> ezplot( 1 / (5 + 4*cos(x)) );
>> hold on;
>> g = x^2 + y^2 - 3;
>> ezplot(g);
>> [x0,y0]=solve(' x^2 + y^2 - 3 = 0', 'y = 1 / (5 +
4*cos(x))')
x0 =
-1.7171874987452662214405745566175
y0 =
0.22642237997374799956828634725117
>> plot(x0,y0,'o')
>> ezplot( diff( 1 / (5 + 4*cos(x)), x) )
>> axis equal
23 Symbolic Math
Solving System of Non Linear Equation
F(x) = 0 >> syms x1 x2
x = fsolve(fun,x0) >> [x1 x2]=solve('exp(-exp(-(x1+x2))) -
x2*(1+x1^2)', 'x1*cos(x2) + x2*sin(x1) - 0.5')
[x,fval] = fsolve(fun,x0)
x1 =
0.35324661959671746608371888721268
x2 =
fun = @root2d;
x0 = [0,0]; 0.60608173664146473530299588999127
x = fsolve(fun,x0)
x = 0.3532 0.6061
function F = root2d(x)
F(1) = exp(-exp(-(x(1)+x(2)))) -
x(2)*(1+x(1)^2);
F(2) = x(1)*cos(x(2)) +
x(2)*sin(x(1)) - 0.5;
23 Symbolic Math
Differentiation
Use diff to do symbolic differentiation.
>> syms m x b th n y
>> y = m*x + b;
>> diff(y, x) → ans = m
>> diff(y, b) → ans = 1
>> syms x y t
>> S=exp(x^4);
>> diff(S)
ans =
4*x^3*exp(x^4)
>> diff(S,2)
ans =
12*x^2*exp(x^4)+16*x^6*exp(x^4)
23 Symbolic Math
Integration
>> clear
>> syms m b x
>> y = m*x + b;
Indefinite integrals
Definite integrals
>> dsolve('Ds=a*x^2')
ans =
a*t*x^2 + C1
>> dsolve('Ds=a*x^2','x')
ans =
(a*x^3)/3 + C1
>> dsolve('Ds=a*x^2','a')
ans =
(a^2*x^2)/2 + C2
23. Symbolic Math
More differential equations
Second-order ODEs can be solved:
>> y = dsolve('D2y = -a^2*y', ...
'y(0) = 1, Dy(pi/a) = 0')
→ y = exp(a*i*t)/2 + 1/(2*exp(a*i*t))
[t,y] = solver_name(ODEfun,tspan,y0)
Function file
D.Es
function dYdt = odefun(t,Y)
dY1/dt = Y2 dYdt=[Y(2);-5*sin(Y(1))];
dY2/dt = -5*sin(Y1)
dY1/dt(0)=Y2(0)=0
24. Diff. Equation Solvers
Question
• Plot the results, which are now stored as sol.x and sol.y.
plot(sol.x,sol.y(1,:),'b-x');
24. Diff. Equation Solvers
• For e.g % Function to solve d^2y/dx^2+y = 0.
d2y/dx2 −y=0
xmesh A vector [x0, x1, ..., xn] specifying the points at which a
numerical solution is requested for every value in tspan. The
elements of xmesh must satisfy x0 < x1 < ... < xn. The length
of xmesh must be >= 3.
tspan A vector [t0, t1, ..., tf] specifying the points at which a
solution is requested for every value in xmesh. The elements
of tspan must satisfy t0 < t1 < ... < tf. The length
of tspan must be >= 3.
24. Diff. Equation Solvers
Partial Derivative
PDEs of the form −m m
c(x,t,u,∂u/∂x) ∂u/∂t=x ∂/∂x(x f(x,t,u,∂u/∂x))+s(x,t,u,∂u/∂x)
:
pdefun computes the terms c, f, and s
[c,f,s] = pdefun(x,t,u,dudx)
u(x,0)=sinπx % --------------------------------
------------------------------
function [pl,ql,pr,qr] =
pdex1bc(xl,ul,xr,ur,t)
and boundary conditions pl = ul;
ql = 0;
pr = pi * exp(-t);
u(0,t)≡0 qr = 1;
πe−t+∂u/∂x(1,t)=0
24. Diff. Equation Solvers
%Contunue……………………………………….
m = 0;
x = linspace(0,1,20);
t = linspace(0,2,5);
sol = pdepe(m,@pdex1pde,@pdex1ic,@pdex1bc,x,t);
% Extract the first solution component as u.
u = sol(:,:,1);
sol = pdepe(m,@pdex4pde,@pdex4ic,@pdex4bc,x,t);
u1 = sol(:,:,1);
u2 = sol(:,:,2);
figure
surf(x,t,u1)
title('u1(x,t)')
xlabel('Distance x')
ylabel('Time t')
figure
surf(x,t,u2)
title('u2(x,t)')
xlabel('Distance x')
ylabel('Time t')
25. Optimization
• Optimization can be define it as “the art of making
things the best.” for e.g In Car industries there are
many thing that need to be optimized. From fuel
efficiency to pollution minimization or noise
reduction, drag reduction and various other
important performance attributes.
25. Optimization
Optimization Functions in MATLAB
Command and its Description
• bintprog Binary integer programming problems
• fgoalattain Multiobjective goal attainment problems
• fminbnd Minimum of single-variable function on fixed interval
• fmincon Minimum of constrained nonlinear multivariable
function
• fminimax Minimax constraint problem
• fminsearch Minimum of unconstrained multivariable function
using derivative-free method
• fminunc Minimum of unconstrained multivariable function
• fseminf Minimum of semi-infinitely constrained multivariable
• nonlinear function
• linprog Linear programming problems
• quadprog Quadratic programming problems
25. Optimization
To find Maximum or minimum of a function
x = fminbnd(function,x1,x2)
[x,fval] = fminbnd(function,x1,x2)
fminbnd is a one-dimensional minimizer that finds a
minimum for a problem specified by minxf(x) such
that x1<x<x2.
x, x1, and x2 are finite scalars, and f(x) is a function
that returns a scalar
25. Optimization
find the location of the local minimum of
f(x) = x3 – 12x2 + 40.25x – 36.5 in 3 ≤ x ≤ 8
>> [x fval]=fminbnd('x^3-12*x^2+40.25*x-36.5',3,8)
x =
5.6073
fval =
-11.8043
25. Optimization
(linear programming )
linprog :-Solve linear programming problems
collapse all in page
x = linprog(f,A,b)
x = linprog(f,A,b,Aeq,beq)
x = linprog(f,A,b,Aeq,beq,lb,ub)
[x,fval] = linprog(___)
25. Optimization
(linear programming )
Linear Program, Linear Inequality Constraints
Solve a simple linear program defined by linear inequalities. For this example, use these
linear inequality constraints
b = [2 1 2 1 -1 2];
x = linprog(f,A,b)
x =
0.6667
1.3333
25. Optimization
(linear programming )
Linear Program, Linear Inequality Constraints, Inequality Constraints, Bounds
f = [-1 -1/3];
A = [1 1
1 1/4 In equality
1 -1 constraints
Objective
-1/4 -1
-1 -1
Function
-1 1];
b = [2 1 2 1 -1 2];
Aeq = [1 1/4];
beq = 1/2; Equality
lb = [-1,-0.5]; Constraints
ub = [1.5,1.25];
x = linprog(f,A,b,Aeq,beq,lb,ub)
x =
bounds:
0.1875
1.2500
25. Optimization
(Non-linear)
Find minimum of constrained nonlinear multivariable function.
Nonlinear programming solver.
Finds the minimum of a problem specified by
b and beq are vectors, A and Aeq are matrices, c(x) and ceq(x) are
functions that return vectors, and f(x) is a function that returns a scalar.
f(x), c(x), and ceq(x) can be nonlinear functions.
25. Optimization
(Non-linear)
x = fmincon(fun,x0,A,b)
x = fmincon(fun,x0,A,b,Aeq,beq)
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub)
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon)
[x,fval] = fmincon(___)
25. Optimization
(Non-linear)
Linear Inequality Constraint
For e.g minimize
Find the minimum value starting from the point [-1,2]
Constraint
0.5022 0.2489
25. Optimization
(Non-linear)
Linear Inequality and Equality Constraint
from previous problem
Find the minimum value starting from the point [0.5,0],
constrained to have
0.4149 0.1701
25. Optimization
(Non-linear)
Bound Constraints
For e.g F(x)=1 + x(1)/(1+x(2)) – 3.x(1).x(2) + x(2).(1 + x(1))
Bound within x(1) ≤ 1, x(2) ≤ 2
1.0000 2.0000
25. Optimization
(Non-linear)
% create file nlcon.m for nonlinear constraints
function [c,ceq] = nlcon(x)
c = 25.0 - x(1)*x(2)*x(3)*x(4);
ceq = sum(x.^2) - 40;
% initial guess
x0 = [1,5,5,1];
% variable bounds
lb = 1.0 * ones(4);
ub = 5.0 * ones(4);
% linear constraints
A = [];
b = [];
Aeq = [];
beq = [];
% nonlinear constraints
nonlincon = @nlcon;
syms s t a b w syms s t a b w
laplace(a)
ilaplace(1/s^7)
ans =
1/s^2 ans =
t^6/720
laplace(t^2)
ans = ilaplace(2/(w+s))
2/s^3
ans =
laplace(t^9) 2*exp(-t*w)
ans =
362880/s^10 ilaplace(s/(s^2+4))
ans =
laplace(exp(-b*t)) cos(2*t)
ans =
1/(b + s)
Taking the Laplace transform and considering zero initial conditions we have
25. Matlab in Control System
Continue…….
The transfer function between u(t) and y(t) is given by:
where G(s) = M(s)/N(s) is the transfer function of the system; the roots
of N(s) are called poles of the system and the roots of M(s) are called
zeros of the system. By setting the denominator function to zero, we
obtain the characteristic equation:
25. MATLAB in Control System
(Partial Fraction)
Partial Fraction of Transfer Function
[r,p,k] = residue(b,a)
[b,a] = residue(r,p,k)
[r,p,k] = residue(b,a) finds the residues, poles, and direct
term of a Partial Fraction Expansion of the ratio of two polynomials,
where the expansion is of the form
-12
[b,a] =
8 residue(r,p,k)
p =
b =
-4
-2 -4 8
k =
a =
[]
This represents the partial fraction expansion
1 6 8
25. MATLAB in Control System
Continue……
b = [2 1 0 0];
a = [1 0 1 1];
[r,p,k] = residue(b,a)
r =
0.5354 + 1.0390i
0.5354 - 1.0390i
-0.0708 + 0.0000i
p =
0.3412 + 1.1615i
0.3412 - 1.1615i
-0.6823 + 0.0000i
k = 2
residue returns the complex roots and poles, and a constant term in k, representing the partial fraction expansion
25. MATLAB in Control System
Continue……
b = [2 0 0 1 0];
a = [1 0 1];
[r,p,k] = residue(b,a)
r =
0.5000 - 1.0000i
0.5000 + 1.0000i
p =
0.0000 + 1.0000i
0.0000 - 1.0000i
k =
2 0 -2
Where k = 2s2 - 2
25. MATLAB in Control System
Block Diagrams:- A block diagram of a system is a pictorial representation of the functions
performed by each component and of the flow of signals. The block diagram gives an overview
of the system.
C num = [3 1];
den = [1 3 2];
G = tf(num,den)
Transfer function:
3 s + 1
-------------
s^2 + 3 s + 2
25. MATLAB in Control System
• Evaluate the transfer function of the
feedback system shown in the figure
above using MATLAB where G1(s) = 4,
G2(s) = 1/(s+2) and H(s) = 5s.
G1 = tf([0 4],[0 1]);
G2 = tf([0 1],[1 2]);
H = tf([5 0],[0 1]);
SYS = feedback(G1*G2,H)
Transfer function:
4
--------
21 s + 2
25. MATLAB in Control System
Time Response Analysis with MATLAB :-
Step response:-
• To plot the unit-step response of the LTI system
SYS=tf(num,den) in MATLAB, we use the
command step(SYS) Or step(num,den)
num = [0 2 10];
den = [1 5 4];
SYS = tf(num,den);
step(SYS)
or directly:
step(num,den)
t = 0:0.1:10; % Time axis from 0 sec to
10 sec in steps of 0.1 sec
and then introducing this time range in the step function as
follows:
step(SYS,t) % Plot the step response for
the given time range, t
25. MATLAB in Control System
Impulse response
• The unit-impulse response of a control system
SYS=tf(num,den) may be plotted in
MATLAB using the function impulse(SYS).
num = [0 5];
den = [2 10];
SYS = tf(num,den);
impulse(SYS)
or directly
impulse(num,den)
25. MATLAB in Control System
Ramp response
• There is no ramp command in MATLAB. To obtain the unit ramp response of the transfer function G(s):
– multiply G(s) by 1/s, and
– use the resulting function in the step command.
num = [0 0 0 1];
den = [1 1 1 0];
step(num,den)
25. MATLAB in Control System
Arbitrary response:-
• To obtain the time response of the LTI system
SYS=tf(num,den) to an arbitrary input (e.g. exponential
function, sinusoidal function .. etc.), we can use the lsim
command (stands for 'linear simulation') as follows:
lsim(SYS,r,t) or lsim(num,den,r,t)
num = [0 2];
den = [1 3];
• Then specify the required time range and define the input
function, r, over this time:
• The Ground Block:- The Ground block can be used to connect blocks whose input ports are
not connected to other blocks, the Ground block outputs a signal with zero value. The data
type of the signal is the same as that of the port to which it is connected.
• The Constant and Product Blocks:- The Constant block is used to define a real or complex
constant value. This block accepts scalar (1x1 2−D array), vector (1−D array), or matrix (2−D
array) output. The Product block performs multiplication or division of its inputs.
26. SIMULINK
• The Integrator Block:- The Integrator block integrates its input and it is used with
continuous−time signals.
• The Inport, Outport, and Subsystem Blocks :- Inport blocks are ports that serve as links from
outside a system into the system. Outport blocks are output ports for a subsystem. A
Subsystem block represents a subsystem of the system that contains it. As our model
increases in size and complexity, we can simplify it by grouping blocks into subsystems.
26. SIMULINK
•The Add Block:- The Add block performs addition or
subtraction on its inputs.
This variable contains the time values used in the simulation, important for variable
time integration types
x1 y x1 x 2
x2 y x 2 bo f c1x 2 co x1
x1 0 1 0
x A B
x 2 co c1 bo
uf C 1 0
26. SIMULINK
1st Order State-Space Models
26. SIMULINK
Build Model for D.E
1
5
26. SIMULINK
Step Response for given transfer function :-
26. SIMULINK
Creating Subsystems
• Subsystem – similar to “Subroutine”
• Advantage of Subsystems:
– Reduce the number of blocks display on the main
window (i.e. simplify the model)
– Group related blocks together (i.e. More
organized)
– Can create a hierarchical block diagram (i.e. you
can create subsystems within a subsystem )
– Easy to check for mistakes and to explore different
parameters
26. SIMULINK
Creating Subsystems
Create Subsystem using model in Example 1
STEP 1: Creating Blocks (Main window)
Inport Outport
(named from “sum” (three outports)
26. SIMULINK
Creating Subsystems
STEP 3: Making connections (Main window)
26. SIMULINK
Creating Subsystems
STEP 4: Set Parameter (Main window)
STEP 5: Running Simulation
Then view output response