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

CH-426

MATLAB for Scientists and Engineers

Dr. Parvez khan


Assistant Professor
Dept. of Chemical Engineering
ZHCET AMU ALIGARH
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.
Reference book

MATLAB: An Introduction with Applications


by
Amos Gilat
Syllabus
Unit 1
• MATLAB introduction, windows, files, help
features, array, matrix and vector and cells
manipulation, Input-Output statement, MATLAB
graphics, Workspace handling, solution of specific
problems through MATLAB.
Introduction to MATLAB
• Stands for MATrix LABoratory
• Interpreted language
• Scientific programming environment
• Very good tool for the manipulation of matrices
• Great visualisation capabilities
• Built-in functions
• Easy to learn and simple to use
MATLAB Environment (2016)
1: MATLAB Environment
1. Command Window
2. Command History
3. Current directory
4. Workspace Window
5. Figure Window
6. Edit Window
1.1 Command Window
• Command Window is the window in the MATLAB
environment where commands are executed and
MATLAB’s responses are displayed.

1.2 Command History


• Command history window is the window in the MATLAB
environment that lists all the previous commands entered
at the command prompt, which is helpful for recalling
work that was done in a previous session.
1.3 Current Directory
• Current Directory is the folder in your computer where files will be saved and
where the files you will have direct access to are stored. It is useful to View
folders and m-files.

1.4 Workspace Window


• workspace window is the window in the MATLAB environment that lists all the
variables currently being used in the workspace. Following basic command can
be useful .
Workspace (continued …)
• Display contents of workspace
>> whos
Name Size Bytes Class
a 1x1 8 double array
b 1x1 8 double array
c 1x1 8 double array
Grand total is 3 elements using 24 bytes
>>
• Delete variable(s) from workspace
>> clear a b; % delete a and b from workspace
>> whos
Name Size Bytes Class
c 1x1 8 double array
>> clear all; % delete all variables from workspace
>> whos
11
1.5 Figure Window
• Contains output from graphic commands like plot, mesh etc..
• Given figure window is a output example of mesh command.

1.4 Edit Window


• Edit Window is used to create a new program file, or to modify existing files.
Program can be written, edited and saved. It is also useful to creates and
debugs script and function files.
• This window is opened by clicking on the New Script icon in the Tool strip, or
by clicking on the New icon and then selecting Script from the menu.
2. Help Features
• Following are the methods of getting help in
MATLAB
1. Help Window (Help Browser):- The Help Window contains help
information. This window can be opened from the Help icon in the Tool strip
of the Command Window or the toolbar of any MATLAB window.
2. Help Features
2. By using Command
3. Types Of Files in MATLAB
• There are different types of Files in MATLAB
1. M-Files
2. MAT-Files
3. MEX-Files
4. fig File
5. Mdl File
6. Dat File
7. Txt file
8. Doc and docx files
9. Xls and xlsx files
10. Jpg and jpeg files
Etc.
3.1 M-Files
• An m-file, is a simple text file where you can place MATLAB commands. When
the file runs, MATLAB reads the commands and executes them exactly as it
would if you had typed each command sequentially at the MATLAB prompt.
All m-file names must end with the extension '.m' (e.g. test.m).

MATLAB allows writing two kinds of program files −

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

• Functions − functions files are also program files with .m extension.


Functions can accept inputs and return outputs. Internal variables are local to
the function.
3.2 MAT files
• MAT files are binary (or text) files with a .mat extension
contain MATLAB formatted data, and data can be loaded from or written to
these files using the functions LOAD and SAVE, respectively.

3.3 MEX files


• A MEX file is a type of computer file that provides an interface
between MATLAB and functions written in C, C++ or Fortran. It stands for
"MATLAB executable“.
4. Character set
• Character can be Classified into Four
Categories:-
1. Alphabets (A-Z, a-z)
2. Numerals (0-9)
3. Special Characters (&, *, % etc )
4. White Space Characters (tab, new line etc.)
5. Constants
Constant can be of two types:-
1. Numeric Constant
1. Integer constants/Numbers (+1 -1 +2 -2)
2. Real Constant/Numbers (1.23556)
3. Complex constants/Numbers(1+2i)
2. Character Constant
1. Single Character Constants (‘g’ ‘t’)
2. String Constants(‘java’ ‘1947’)
5. Constants
Special Constant:-
6. Variables
Variable:-
A variable is a name made of a letter or a combination
of several letters (and digits) that is assigned a numerical
value. Once a variable is assigned a numerical value, it can
be used in mathematical expressions, in functions, and in
any MATLAB statements and commands. A variable is
actually a name of a memory location.
6. Variables
• Don’t have to declare type
• Don’t even have to initialise
• Just assign in command window
>>
>> a=12; % variable a is assigned 12

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

logspace(xi,xf,n) command is a 1-by-N row vector of logarithmically


spaced numbers, starting at 10xi, and ending at 10xf
for e.g
>> w=logspace(0,4,3)
w=
1 100 10000
Command Related to vectors
12.3 Matrix
• A two-dimensional array, also called a matrix, has numbers in rows and
columns.
variable_name=[1st row elements; 2nd row elements; 3rd row elements; ... ;
last row elements]
Other methods to create matrix are using ellipsis(…) and carriage return
For e.g
>> a=[5 35 43; 4 76 81; 21 32 40]; or
>> a=[5 35 43; 4 76...
81; 21 32 40]; or
>> a=[5 35 43
4 76 81
21 32 40];

All will return


a=
5 35 43
4 76 81
21 32 40
12.3 Matrix
(Addressing)
Columns
(n)
1 2 3 4 5
A= 4
1
10
6
1
11
6
16
2
21
A (2,4)
1
2 7 12 17 22
2 8 1.2 9 4 25

Rows (m) 3 7.2 3 5 8


7 13
1 18
11 23 A (17)
4 0 4
0.5 9 4 14
5 19
56 24
5 10 15 20 25
5 23 83 13 0 10 Rectangular Matrix:
Scalar: 1-by-1 array
Vector: m-by-1 array
1-by-n array
Matrix: m-by-n array
12.3 Matrix
(Matrix Concatenation)
Use [ ] to combine » a=[1 2;3 4]
existing arrays as a = Use square
matrix “elements” 1 2 brackets [ ]
3 4
» cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]
Row separator: cat_a =
semicolon (;) 1 2 2 4
3 4 6 8
Column separator: 3 6 4 8
4*a
space / comma (,) 9 12 12 16
5 10 6 12
15 20 18 24

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

>> A ' % transpose B=

>> B*A % matrix multiplication 1


4
3
9
1
5
>> B.*A % element by element multiplication 2 7 2

>> B/A % matrix division


>> B./A % element by element division
>> [B A] % Join matrices (horizontally)
>> [B; A] % Join matrices (vertically)

Create matrices A and B and try out the the matrix operators in this slide
12.3 Matrix
(Deleting Rows and Columns)

» A=[1 5 9;4 3 2.5; 0.1 10 3i+1]


A =
1.0000 5.0000 9.0000
4.0000 3.0000 2.5000
0.1000 10.0000 1.0000+3.0000i
» A(:,2)=[]
A =
1.0000 9.0000
4.0000 2.5000
0.1000 1.0000 + 3.0000i
12.3 Matrix
(Reshaping matrix)
• Reshape a 1-by-10 vector into a 5-by-2 matrix.

>> 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,‘r’) A red solid line


connects the points.

•plot(x,y,‘--y’) A yellow dashed


line connects the points.

•plot(x,y,‘*’) The points are


marked with * (no line between the
points).

•plot(x,y,‘g:d’) A green dotted


line connects the points that are marked
with diamond markers.
15.1 2-D Plots
(Property Name and Property Value)
• plot(x,y,‘m-
o’,‘LineWidth’,2,
‘markersize’,12,‘
MarkerEdgeColor’,
‘g’,‘markerfaceco
lor’,‘y’):-creates a
plot that connects the
points with a magenta
solid line and circles as
markers at the points. The
line width is 2 points and
the size of the circle
markers is 12 points. The
markers have a green
edge line and yellow
filling.
15.1 2-D Plots
(PLOTTING MULTIPLE GRAPHS IN THE SAME
PLOT)
1. Using the plot Command
plot(x,y,u,v,t,h)
creates three graphs—y vs. x, v vs. u, and h
vs. t—all in the same plot.

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.

grid on Adds grid lines to the plot.


grid off Removes grid lines from the plot.
15.1 2-D Plots (Special Type)
PLOTS WITH LOGARITHMIC
AXES
• semilogy(x,y) Plots
y versus x with a log (base
10) scale for the y axis and
linear scale for the x axis.
• semilogx(x,y) Plots
y versus x with a log (base
10) scale for the x axis and
linear scale for the y axis.
• loglog(x,y) Plots y
versus x with a log (base
10) scale for both axes.
15.1 2-D Plots (Special Type)
15.1 2-D Plots (Special Type)
• HISTOGRAMS commands
hist(y);
hist(y,nbins);
hist(y,x)
y is a vector with the data
points. MATLAB divides the
range of the data points into
10 equally spaced subranges
(bins) and then plots the
number of data points in
each bin.
• nbins is a scalar that
defines the number of bins.
MATLAB divides the range in
equally spaced subranges.
• x is a vector that specifies
the location of the center of
each bin (the distance
between the centers does
not have to be the same for
all the bins). The edges of the
bins are at the middle point
between the centers.
15.1 2-D Plots (MULTIPLE PLOTS ON THE
SAME PAGE)
Multiple plots can be created on
the same page with the subplot
commandThe subplots are arranged
like elements in an m × n matrix
where each element is a subplot.
subplot(m,n,p)
For example, the command
subplot(3,2,1) creates six areas
arranged in three rows and two
columns as shown, and makes the
upper left subplot current.
15.1 2-D Plots (MULTIPLE FIGURE)
The command figure is entered MATLAB
opens a new Figure Window.
15.1 2-D Plots (Special Type)
• POLAR PLOTS Command
polar(theta,radius,‘line specifiers’)
where theta and radius are vectors whose elements define the
coordinates of the points to be plotted.
15.2 3-D Plots
A basic 3-D plot is created with the plot3 command
15.2 3-D Plots(MESH AND SURFACE PLOTS)
Mesh and surface plots are created in three
steps. The first step is to create a grid in the x y
plane.
Creating a grid in the x y plane
[X,Y] = meshgrid(x,y)
15.2 3-D Plots(MESH AND SURFACE PLOTS)

• 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

• Input Command to define numerical value use in script files


variable_name = input(‘string with a message
that is displayed in the Command Window’)
• Input Command to define String use in script files
variable_name = input(‘prompt message’,‘s’)

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

help lines for function

for statement block

Make sure you save changes to the


m-file before you call the function!

77
Functions (continued)
Functions can have many
>> [i j]=sort2(2,4) outputs contained in a matrix
i=
4
j=
2
if statement
>> block

Remember to use the


Matlab help command for
syntax
>> help if

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

4) >> [p,d] = Fstatistic ([4 3 2 10 -1])

p = 3.6000
d = 3.6111

5) >> edit Fs1.m clc


clear all
6) Write into the editor: x = [4 3 2 10 -1];
7) Save the file [avg,std1]=Fstatistic(x)
avg = 3.6000
std1 = 3.6111
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

4) >> [p,d] = Fstatistic ([4 3 2 10 -1])

p = 3.6000
d = 3.6111

5) >> edit Fs1.m clc


clear all
6) Write into the editor: x = [4 3 2 10 -1];
7) Save the file [avg,std1]=Fstatistic(x)
avg = 3.6000
std1 = 3.6111
19.3 Function file
function [avg,std1,a,c,b] = check1 (x,y)
x
1) >> edit y
check.m n = length(x)
sum1 = sum(x)
2) Write into the editor: avg = sum1/n
3) Save the file std1 = sqrt(mean((x-avg).^2))
a=(x./y)
b= sum(a)
c=b/n
end
5) >> edit Fs1.m

6) Write into the editor:


7) Save the file
clc
avg = 3.6000 clear all
std1 = 3.6111 x = [4 3 2 10 -1];
a= 2 3 1 2 -1 y = [2 1 2 5 1];
b=7 [avg,std1,a,b,c] = check1 (x,y)
c=1.400
Function definition line Comments
function [mpay,tpay] = loan(amount,rate,years) Three input
arguments, two output arguments.
function [A] = RectArea(a,b) Two input
arguments, one output argument.
function A = RectArea(a,b) Same as above;
one output argument can be typed without the brackets.
function [V, S] = SphereVolArea(r) One input
variable, two output variables

function trajectory(v,h,g) Three input


arguments, no output arguments.
Function definition line.

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;

a1=4.5; b1=2.25; T1=40; T2=92; alpha=23e-6;


deltaT=FtoC(T2)-FtoC(T1);
a2=a1+alpha*a1*deltaT;
b2=b1+alpha*b1*deltaT;
AreaChange=a2*b2-a1*b1;
fprintf('The change in the area is %6.5f meters
square.',AreaChange)

The change in the area is 0.01346 meters square.


19.2 Other Types of Function
• ANONYMOUS FUNCTION
• INLINE FUNCTION
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
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

4) >> [p,d] = Fstatistic ([4 3 2 10 -1])

p = 3.6000
d = 3.6111

5) >> edit Fs1.m clc


clear all
6) Write into the editor: x = [4 3 2 10 -1];
7) Save the file [avg,std1]=Fstatistic(x)
avg = 3.6000
std1 = 3.6111
19.2 ANONYMOUS FUNCTION
ANONYMOUS FUNCTION
name = @ (arglist) expr
name:The name of the anonymous function.
@(arglist):-A list of input arguments(independent variables).
expr:- Mathematical expression.
For E.g

>> FA = @ (x) exp(x^2)/sqrt(x^2+5)


FA =
@(x)exp(x^2)/sqrt(x^2+5)
>> FA(2)
ans =
18.1994
>> z = FA(3)
z =
2.1656e+003+
19.2 INLINE FUNCTION
name = inline(‘math expression’,’arg’)

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

4) >> [p,d] = Fstatistic ([4 3 2 10 -1])

p = 3.6000
d = 3.6111

5) >> edit Fs1.m clc


clear all
6) Write into the editor: x = [4 3 2 10 -1];
7) Save the file [avg,std1]=Fstatistic(x)
avg = 3.6000
std1 = 3.6111
19.2 ANONYMOUS FUNCTION
ANONYMOUS FUNCTION
name = @ (arglist) expr
name:The name of the anonymous function.
@(arglist):-A list of input arguments(independent variables).
expr:- Mathematical expression.
For E.g

>> FA = @ (x) exp(x^2)/sqrt(x^2+5)


FA =
@(x)exp(x^2)/sqrt(x^2+5)
>> FA(2)
ans =
18.1994
>> z = FA(3)
z =
2.1656e+003
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.

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

>> Grades=[80 75 91 60 79 89 65 80 95 50 81];


>> [AveGrade StanDeviation] = stat(Grades)

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

>> Grades=[80 75 91 60 79 89 65 80 95 50 81];


>> [AveGrade StanDeviation] = stat(Grades)

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

>> p1=[3 15 0 -10 -3 15 -40];


>> p2=[3 0 -2 -6];
>> p=p1+[0 0 0 p2]
p =
3 15 0 -7 -3 13 -46
19 POLYNOMIALS
Multiplication: Division:
Two polynomials can be A polynomial can be divided by another
multiplied using the MATLAB polynomial with the MATLAB built-in
built-in function conv, which
has the form: function deconv, which has the form:

[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

• k = polyder(p) Derivative of a single polynomial. p is a vector


with the coefficients of the polynomial. k is a vector with the
coefficients of the polynomial that is the derivative.

• k = polyder(a,b) Derivative of a product of two


polynomials. a and b are vectors with the coefficients of the
polynomials that are multiplied. k is a vector with the coefficients of
the polynomial that is the derivative of the product.

• [n d] = polyder(u,v) Derivative of a division of two


polynomials. u and v are vectors with the coefficients of the
numerator and denominator polynomials. n and d are vectors with
the coefficients of the numerator and denominator polynomials of
the derivative.
19 POLYNOMIALS
Derivatives of Polynomials
19 POLYNOMIALS
Integration of Polynomials
q = polyint(p,k)
q = polyint(p)
• p is a vector with the coefficients of the polynomial
• K is a a constant of integration
• q = polyint(p,k) returns the integral of the polynomial represented by the coefficients
in p using a constant of integration k.
• q = polyint(p) assumes a constant of integration k = 0.

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

y is a vector with the vertical


coordinates of the data points
(dependent variable).

n is the degree of the polynomial.


Curve Fitting with Functions Other
than Polynomials
Problem : Fitting an equation to data points
t [0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0]
w [6.00 4.83 3.70 3.15 2.41 1.83 1.49 1.21 0.96 0.73 0.64]

 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’)

yi is the interpolated value.


x is a vector with the horizontal coordinates of the input data points (independent variable).
y is a vector with the vertical coordinates of the input data points (dependent variable).
xi is the horizontal coordinate of the interpolation point (independent variable).
method is method of interpolation, typed as a string (optional). MATLAB can do the
interpolation using one of several methods that can be specified. These methods include:
• ‘nearest’ returns the value of the data point that is nearest to the interpolated point.
• ‘linear’ uses linear spline interpolation.
• ‘spline’ uses cubic spline interpolation.
• ‘pchip’ uses piecewise cubic Hermite interpolation, also called ‘cubic’
22 Interpolation
e.g. f(x) = 1.5x cos(2x)
X=[0 1 2 3 4 5]
Y=[1.0 –0.6242 –1.4707 3.2406 –0.7366 –6.3717]

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)

b: vector of regression coefficients


bint: matrix of 95% confidence intervals for B
r: vector of residuals
23 Multiple linear regression
y=b1*x+b2

>> x=[.2 .5 .6 .8 1.0 1.1]';


>> y=[.17 .26 .28 .23 .27 .24]';
>> X=[ones(size(x)) x];
>> [b,bint,r]=regress(y,X)
b =

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

>> x=[.2 .5 .6 .8 1.0 1.1]'; b =


>> x1=[.1 .3 .4 .9 1.1 1.4]';
>> y=[.17 .26 .28 .23 .27 .24]';
0.0832 0.1204
>> X=[ones(size(x)) x x1];
>> b=regress(y,X)
0.4188 0.5500
b = -0.3277 -0.2416

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

>> x=[.2 .5 .6 .8 1.0 1.1]';


>> x1=[.1 .3 .4 .9 1.1 1.4]';
>> y=[.17 .26 .28 .23 .27 .24]';
>> X=[ones(size(x)) x x1];
>> X\y

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)

• The function can be entered as a string expression, or as a


function handle, in the same way as with the ‘fzero’ command.
• You can also calculate function value:
[x fval]=fminbnd(function,x1,x2)

• The fminbnd command can also used to calculate the maximum


value of function.
• This can be done by multiplying the function by –1 and finding
the minima.
SOLVING AN EQUATION WITH ONE VARIABLE
Problem: find minima of the function
Sol: 𝑓 𝑥 = 𝑥 3 − 12𝑥 2 + 40.25𝑥 − 36.5
>> fplot('x^3-12*x^2+40.25*x-36.5',[0 8])
>> [x fval]=fminbnd('x^3-12*x^2+40.25*x-36.5',3,8)
x = 5.6073
Fval = -11.8043
>> [x fval]=fminbnd('x^3-12*x^2+40.25*x-36.5',0,8)
x=0
fval = -36.5000
Maxima
>> [x fval]=fminbnd('-x*exp(-x)+0.2',0,8)
x=
1.0000
fval =
-0.1679
NUMERICAL INTEGRATION
q = quad(function,a,b)

• The function can be entered as a string expression, or as a


function handle, in the same way as with the ‘fzero’ command.
• The function must be written for an argument x that is a vector
(use element-by-element operations) such that it calculates the
value of the function for each element of x.
• You can also calculate integral with an absolute error.
q = quad(function,a,b,tol)

• The fminbnd command can also used to calculate the maximum


value of function.
• This can be done by multiplying the function by –1 and finding
the minima.
NUMERICAL INTEGRATION
Problem: Use numerical integration to calculate the following integral:
8 −𝑥 0.8 +0.2) 𝑑𝑥
0
(𝑥𝑒
Sol:
>> quad('x.*exp(-x.^0.8)+0.2',0,8)
ans =
3.1604
>> F=@(x)x.*exp(-x.^0.8)+0.2
ans =3.1604
function y=Fdemo(x)
y=exp(-0.17*x).*x.^3-2*x.^2+0.8*x-3;

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

function g = rdf1 (x)


g= exp(x.^2) +sqrt(x)
end

function g = rdf2 (x)


g= exp(x.^3) +sqrt(x) +1
end

S1 = entropy (@rdf1, 0.5, 0.5, 10, 1,100)


S2 = entropy (@rdf2, 0.6, 0.4, 10, 1,100)
S3 = entropy (@rdf3, 0.7, 0.8, 10, 1,100)
solving algebraic equations (Using Matrix)
18 Control Structutre
1. The if-end Structure
2. The if-else-end Structure
3. The if-elseif-else-end Structure
4. The switch-case statement
18.1 The if-end Structure
18.2 The if-else-end Structure
18.3 The if-elseif-else-end
Structure
18.4 The switch-case statement
24 Symbolic Math
What is Symbolic Math?
Symbolic mathematics deals with equations before you plug in
the numbers.

• Calculus – integration, differentiation, Taylor series


expansion, …
• Simplification – algebraic and trigonometric expressions
• Equation Solutions – algebraic and differential equations
• Transforms – Fourier, Laplace, Z transforms and inverse
transforms, …
23 Symbolic Math
Symbolic Objects
Symbolic objects can be variables or numbers. They can be
created with the sym and/or syms commands.

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

>> sym(2)/sym(5) + sym(1)/sym(3)


ans = 11/15
23 Symbolic Math
Symbolic expressions
>> syms a b c x y
>> f=a*x^2+b*x + c
f =
a*x^2 + b*x + c

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

>> a=sym(3); b=sym(5);


>> e=b/a+sqrt(2)
e=
2^(1/2) + 5/3
>> c=3; d=5; >> g=d/a+sqrt(2)
>> f=d/c+sqrt(2) g=
f= 2^(1/2) + 5/3
3.0809
23 Symbolic Math
Symbolic expressions
>> syms x y
>> SA=x+y, SB=x-y
SA =
x+y
SB =
x-y
>> F=SA^2/SB^3+x^2
F=
(x+y)^2/(x-y)^3+x^2
23 Symbolic Math
Substituting into symbolic expressions
The subs function substitutes values or expressions for
variables in a symbolic expression.

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

Expressions can be substituted into variables.

>> subs(f, z*pi) → ans = cos(pi*z)


23 Symbolic Math
The findsym Command
findsym(S) or findsym(S,n)

>> 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('m*x + b - (n*x + c)', 'x') → ans = -(b - c)/(m - n)


>> solve('m*x + b - (n*x + c)', 'b') → ans = c - m*x + n*x
>> collect(ans, 'x') → ans = c - x*(m - n)

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

>> [x y z]=solve('4*x-2*y+6*z-8', '2*x+8*y+2*z-4', ...


'6*x+10*y+3*z')
x=
-74/41

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 ]

>> [x, y] = solve('m*x + b = y', 'y = n*x + c')


→ Unique solution: x = -(b - c)/(m - n)
y = -(b*n - c*m)/(m - n)

If there is no analytic solution, a numeric solution is attempted.


>> [x,y] = solve('sin(x+y) - exp(x)*y = 0', ...
'x^2 - y = 2')
→ x = -0.66870120500236202933135901833637
y = -1.5528386984283889912797441811191
23 Symbolic Math
Solving systems of equations
Systems of equations can be solved.
(If the number of variables is greater than the number of equations)

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

>> [tx yx]=solve(S,'5*x-y=13*t',y,t)


tx =
x/2
yx =
-(3*x)/2
23 Symbolic Math
Solving systems of equations
The equation of a circle in the x y plane with radius R and its center at point (2, 4)is
given by (x-2)^2+(y-4)^2=R^2. The equation of a line in the plane is given by
y=x/2+1. Determine the coordinates of the points (as a function of R) where theline
intersects the circle.

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

>> p = sin(th)^n → p = sin(th)^n


>> diff(p, th) → ans = n*cos(th)*sin(th)^(n - 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

>> int(y, x) → ans = (m*x^2)/2 + b*x


>> int(y, b) → ans = (b + m*x)^2/2
>> int(1/(1+x^2)) → ans = atan(x)

Definite integrals

>> int(y,x,2,5) → ans = 3*b + (21*m)/2


>> int(1/(1+x^2),x,0,1) → ans = pi/4
23. Symbolic Math
Solving differential equations
We want to solve:

Use D to represent differentiation against the independent


variable.
>> y = dsolve('Dy = -a*y')
→ y = C5/exp(a*t)
>> dsolve('D2x+2*Dx+x=0') 𝑑2 𝑥
2 + 2
𝑑𝑥
+ x=0
𝑑𝑡 𝑑𝑡
ans =
C1/exp(t)+(C2*t)/exp(t)

Initial values can be added:


>> y = dsolve('Dy = -a*y', 'y(0) = 1')
→ y = 1/exp(a*t)
23. Symbolic Math
Solving differential equations
𝑑𝑠
We want to solve: = 𝑎𝑥 2
𝑑𝑡

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

Systems of ODEs can be solved:


>> [x,y] = dsolve('Dx = y', 'Dy = -x')
→ x = (C13*i)/exp(i*t) - C12*i*exp(i*t)
y = C12*exp(i*t) + C13/exp(i*t)
24. Diff. Equation Solvers
Ordinary Differential Equations
• Ordinary differential equations.
• Partial differential equations.
• Linear differential equations.
• Non-linear differential equations.
24. Diff. Equation Solvers
Ordinary Differential Equations
(Initial Value Problems)
Steps for solving a single first-order ODE
Step 1: Write the problem in a standard form.
Step 2: Create a user-defined function (in a function
file) or an anonymous function.
Step 3: Select a method of solution.
Step 4: Solve the ODE.
[t,y] = solver_name(ODEfun,tspan,y0)
24. Diff. Equation Solvers

[t,y] = solver_name(ODEfun,tspan,y0)

solver_name:-Is the name of the solver (numerical


method) that is used (e.g. ode45 or ode23s).
ODEfun:- The function from Step 2.
tspan:-A vector that specifies the interval of the
solution.
y0:- The initial value of y
[t,y]:- The output, which is the solution of the
ODE. t and y are column vectors.
24. Diff. Equation Solvers
ODE Solver and its Description

• ode45 For nonstiff problems, one-step solver, best to apply as a


first try for most problems. Based on explicit Runge-Kutta method.
• ode23 For nonstiff problems, one-step solver. Based on explicit
Runge-Kutta method. Often quicker but less accurate than ode45.
• ode113 For nonstiff problems, multistep solver.
• ode15s For stiff problems, multistep solver. Use if ode45 failed.
Uses a variable order method.
• ode23s For stiff problems, one-step solver. Can solve some
problems that ode15s cannot.
• ode23t For moderately stiff problems.
• ode23tb For stiff problems. Often more efficient than ode15s.
24. Diff. Equation Solvers

>> Creating Function file


[t,y]=ode45(@ODEexp1,[1:0.5:3],4.2)
t =
1.0000 function dydt=ODEexp1(t,y)
1.5000 dydt=(t^3-2*y)/t;
2.0000
2.5000
Initial Or
3.0000
Value
y =
4.2000 >> ode1=@(t,y)(t^3-2*y)/t
2.4528 domain
ode1 =
2.6000
3.7650
@(t,y)(t^3-2*y)/t
5.8444
OR >> tspan= [1:0.5:3]
>> tspan = [1:0.5:3]
>> y0 = 4.2
[t,y]=ode45(‘ode1’,tspan,y0)
24. Diff. Equation Solvers
Simultaneous D.Es
For e.g Program
dy1/dt=−y2, y10=1; y20=0;
dy2/dt=y1,
[x,Y] =
Initial condition ode45(@odefun,[0,5],[y10;y20]);
y1(0)=1 and y2(0)=0.
plot(t,Y(:,1),'b',t,Y(:,2),'r');
legend('y_1','y_2')

Function file

function dYdt = odefun(t,Y)


dYdt=[-Y(2);Y(1)];
24. Diff. Equation Solvers
Higher Order Derivatives
d2Y1/dt2 + 5*sin(Y1)=0 Program
y10=1; y20=0;
Initial Conditions
Y1(0)=1 dY1/dt(0)=0 [x,Y] =
ode45(@odefun,[0,20],[y10;y20]);

First Reduce the derivative


Then Solve it as Simultaneous 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

• Solve d2y/dx2+2y/x=x4, subject to y(1)=1.

• Solve d2y/dx2+3dy/dx−4y=0, subject to y(0)=1 and


y'(0)=0.
24. Diff. Equation Solvers
Boundary Value Problems
• Construct a function (here called derive) which has input arguments x and y=(y1,⋯,yn) and
returns the value of the derivative dy/dx, that is f(x,y).
• Construct a function (here called bcs) which has input arguments y(a) and y(b) and returns
the value of the residual for each specified boundary condition. For example to apply
y1(a)=1 and y1(b)=0 use function res = bcs(ya,yb)
res = [ ya(1) – 1 ; yb(1)];
• Define the solution domain and provide an initial guess for the solution on the solution
domain. Use the command solinit = bvpinit([a,b],[0,0]);[This defines the
domain for solution as [a,b], and the initial guess for the solution at the points specified in
the domain as [0,0].]
• Call the ODE solver bvp4c, using the following command

sol = bvp4c or bvp5c(@derive,@bcs,solinit);

• 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. solinit = bvpinit([0,pi],[0,0]);


subject to y'(0)=1
sol = bvp4c(@deriv,@bcs,solinit);
and y(π)=0
plot(sol.x,sol.y(1,:),'b-x');

The exact solution is


y=sin(x). function files
%derive Function
function dYdx = deriv(x,Y)
dy/dx=z, dYdx(1) = Y(2);
dYdx(2) = -Y(1);
dz/dx=−y.
% boundary conditions y'(a)=1, y(b)=0.
function res = bcs(ya,yb)
with z(0)=1 res = [ ya(2) - 1
yb(1)];
and y(π)=0.
24. Diff. Equation Solvers
Boundary Value Problems

Use bvp4c to solve the following boundary value problems.

Consider the equation.

d2y/dx2 −y=0

1. Solve this subject to y'(0)=0 and y(0)=0


2. Solve the same equation this subject to y(0)=0 and y(1)=1
3. Solve the same equation subject to y'(0)=0 and y(1)=1.
24. Diff. Equation Solvers
Partial Derivative
sol = pdepe(m,pdefun,icfun,bcfun,xmesh,tspan)
m A parameter corresponding to the symmetry of the
problem. m can be slab = 0, cylindrical = 1, or spherical = 2.

pdefun A handle to a function that defines the components of the


PDE.
icfun A handle to a function that defines the initial conditions.

bcfun A handle to a function that defines the boundary conditions.

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)

For t = t0 and all x,


u(x,t0)=u0(x)
icfun evaluates the initial conditions. It has the form
u = icfun(x)

For all t and either x = a or x = b


p(x,t,u)+q(x,t)f(x,t,u,∂u/∂x)=0

bcfun evaluates the terms p and q of the boundary conditions


[pl,ql,pr,qr] = bcfun(xl,ul,xr,ur,t)
24. Diff. Equation Solvers
% --------------------------------
For e.g ------------------------------
function [c,f,s] =
π2∂u/∂t=∂/∂x(∂u/∂x) pdex1pde(x,t,u,DuDx)
c = pi^2;
f = DuDx;
This equation holds on an s = 0;
interval 0 ≤ x ≤ 1 for times t ≥ 0
% --------------------------------
The PDE satisfies the initial ------------------------------
condition function u0 = pdex1ic(x)
u0 = sin(pi*x);

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

% A surface plot is often a good way to study a solution.


surf(x,t,u)
title('Numerical solution computed with 20 mesh points.')
xlabel('Distance x')
ylabel('Time t')

% A solution profile can also be illuminating.


figure
plot(x,u(end,:))
title('Solution at t = 2')
xlabel('Distance x')
ylabel('u(x,2)')
24. Diff. Equation Solvers
% ---------------------------------
For e.g. -----------------------------
∂u1/∂t =0.024(∂2u1/∂x2)-F(u1−u2) function [c,f,s] =
∂u2/∂t=0.170(∂2u2/∂x2)+F(u1−u2) pdex4pde(x,t,u,DuDx)
c = [1; 1];
f = [0.024; 0.17] .* DuDx;
y = u(1) - u(2);
F = exp(5.73*y)-exp(-11.47*y);
where F(y) = exp(5.73y) – exp(–11.46y). s = [-F; F];
This equation holds on an interval 0 ≤ x ≤ % ---------------------------------
1 for times t ≥ 0. -----------------------------
function u0 = pdex4ic(x);
The PDE satisfies the initial conditions u0 = [1; 0];
u1(x,0)≡1 % ---------------------------------
-----------------------------
u2(x,0)≡0
function [pl,ql,pr,qr] =
pdex4bc(xl,ul,xr,ur,t)
and boundary conditions pl = [0; ul(2)];
∂u1/∂x(0,t)≡0 ql = [1; 0];
u2(0,t)≡0 pr = [ur(1)-1; 0];
u1(1,t)≡1 qr = [0; 1];
∂u2/∂x(1,t)≡0
24. Diff. Equation Solvers
%Contunue……………………………………….
function pdex4
m = 0;
x = [0 0.005 0.01 0.05 0.1 0.2 0.5 0.7 0.9 0.95 0.99 0.995 1];
t = [0 0.005 0.01 0.05 0.1 0.5 1 1.5 2];

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

Linear programming solver


Finds the minimum of a problem specified by
f, x, b, beq, lb, and ub are vectors, and A and Aeq are matrices.

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

f = [-1 -1/3]; In equality


A = [1 1 Objective constraints
1 1/4 Function
1 -1
-1/4 -1
-1 -1
-1 1];

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

fun = @(x)100*(x(2)-x(1)^2)^2 + (1-x(1))^2;


x0 = [-1,2];
A = [1,2];
b = 1;
x = fmincon(fun,x0,A,b)
x =

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

fun = @(x)100*(x(2)-x(1)^2)^2 + (1-x(1))^2;


x0 = [0.5,0];
A = [1,2];
b = 1;
Aeq = [2,1];
beq = 1;
x = fmincon(fun,x0,A,b,Aeq,beq)
x =

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

fun = @(x)1+x(1)/(1+x(2)) - 3*x(1)*x(2) +


x(2)*(1+x(1));
lb = [0,0];
ub = [1,2];
A = [];
b = [];
Aeq = [];
beq = [];
x0 = [0.5,1];
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub)
x =

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;

objective = @(x) x(1)*x(4)*(x(1)+x(2)+x(3))+x(3);

% initial guess
x0 = [1,5,5,1];

% variable bounds
lb = 1.0 * ones(4);
ub = 5.0 * ones(4);

% show initial objective


disp(['Initial Objective: ' num2str(objective(x0))])

% linear constraints
A = [];
b = [];
Aeq = [];
beq = [];

% nonlinear constraints
nonlincon = @nlcon;

% optimize with fmincon


%[X,FVAL,EXITFLAG,OUTPUT,LAMBDA,GRAD,HESSIAN]
% = fmincon(FUN,X0,A,B,Aeq,Beq,LB,UB,NONLCON,OPTIONS)
x = fmincon(objective,x0,A,b,Aeq,beq,lb,ub,nonlincon);
25. MATLAB in Control System
The Laplace Transform of a function
The Laplace transform of a function of time f(t) is given by the following
integral:-

Laplace transform turns differential equations into algebraic ones. To


compute a Laplace transform of a function f(t), write −
laplace(f(t))

MATLAB allows us to compute the inverse Laplace transform using the


command ilaplace.
ilaplace(g(s))
25. MATLAB in Control System
The Laplace Transformation Inverse Laplace

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)

laplace(sin(w*t)) ilaplace(w/(s^2 + w^2))


ans = ans =
w/(s^2 + w^2) sin(t*w)
25. MATLAB in Control System
An important step in the analysis and design of control systems is the
mathematical modelling of the controlled process. There are a number
of mathematical representations to describe a controlled process:
• Differential equations
• Transfer function: It is defined as the ratio of the Laplace transform of
the output variable to the Laplace transform of the input variable,
with all zero initial conditions.
• Block diagram: It is used to represent all types of systems. It can be
used, together with transfer functions, to describe the cause and
effect relationships throughout the system.
• State-space-representation: You will study this in an advanced Control
Systems Design course.
26. MATLAB in Control System
Mathematical representations to describe a controlled process

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

The inputs to residue are vectors of coefficients of the polynomials b =


[bm ... b1 b0] and a = [an ... a1 a0]. The outputs are the residues r = [rn
... r2 r1], the poles p = [pn ... p2 p1], and the polynomial k.

[b,a] = residue(r,p,k) converts the partial fraction expansion


back to the ratio of two polynomials and returns the coefficients in b
and a.
25. MATLAB in Control System
For e.g
Convert the partial fraction
b = [-4 8]; expansion back to polynomial
a = [1 6 8]; coefficients using residue.
[r,p,k] = residue(b,a)
r =

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

• R(s) = reference input (command)


• Y(s) = output (controlled variable)
• U(s) = input (actuating signal)
• E(s) = error signal
• F(s) = feedback signal
• G(s) = forward path transfer function
• H(s) = feedback transfer fucntion
25. MATLAB in Control System
25. MATLAB in Control 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:

t = 0:0.1:6; % Time range from 0 to 6 sec in


steps of 0.1 sec
r = exp(-t); % Input time function
Enter the above information into the lsim
function by typing:
lsim(num,den,r,t)
26. SIMULINK
Simulink is a simulation and model-based design environment for
dynamic and embedded systems, integrated with MATLAB. Simulink,
also developed by MathWorks, is a data flow graphical programming
language tool for modelling, simulating and analyzing multi-domain
dynamic systems. It is basically a graphical block diagramming tool
with customizable set of block libraries. It allows you to incorporate
MATLAB algorithms into models as well as export the simulation
results into MATLAB for further analysis.
Simulink supports −
• system-level design
• simulation
• automatic code generation
• testing and verification of embedded systems
26. SIMULINK

The Simulink Library Browser


26. SIMULINK
• The Signal Generator Block:- The Signal Generator block
can produce one of four different waveforms: sine wave,
square wave, sawtooth wave, and random wave.

• The Pulse Generator Block:- The Pulse Generator block


generates square wave pulses at regular intervals.

• The Sine Wave Block:- The Sine Wave block generates a


sine wave.

• The Ramp Block:- The Ramp block generates a signal that


starts at a specified time and value and changes by a
specified rate.

• The Step Block:- The Step block generates a step between


two defined levels at some specified time.
26. SIMULINK
• The Terminator Block:- The Terminator block can be used
to cap blocks whose output ports are not connected to
other blocks.

• The Scope Block:- The Scope block displays waveforms as


functions of simulation time.

• The To Workspace Block:- The To Workspace block writes


its input to the workspace.

• The XY Graph Block:- The XY Graph block displays an X−Y


plot of its inputs in a MATLAB figure window.
26. SIMULINK
• The Derivative Block:- The Derivative block
approximates the derivative of its input. The initial
output for the block is zero.

• The Transfer Fcn Block:- The Transfer Fcn block


implements a transfer function

• The Zero−Pole Block:- The Zero-Pole block implements


a system with the specified zeros, poles, and gain in the
s−domain.

• The State−Space Block:- The State-Space block


implements a system defined by the state−space
equations
x·= Ax + Bu
y = Cx + Du
26. SIMULINK
•The Switch Block:- The Switch block will output the
first input or the third input depending on the value of
the second input.

•The Gain Block:- The Gain block multiplies the input


by a constant value (gain).

•The Relational Operator Block:- The Relational


Operator block performs the specified comparison of
its two inputs.
26. SIMULINK
• The Logical Operator Block:- The Logical Operator block performs the specified logical
operation on its inputs.

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

•The Sum Block:- The Sum block is an


implementation of the Add block.

•The Subtract Block:- The Subtract block is an


implementation of the Add block.

•The Product Block:- The Product block performs


multiplication or division of its inputs.

•The Divide Block:- The Divide block is an


implementation of the Product block.
26. SIMULINK
Building Models:-
• To create a new model, click
the New button on the Library
Browser's toolbar. This opens a
new untitled model window.

• Model elements are added by


selecting the appropriate
elements from the Library
Browser and dragging them
into the Model window.

• A signal generator thesource


generates an analog signal,
which will then be graphically
visualized by the scope thesink.
26. SIMULINK
• Drag a 'Sine Wave' block into the
model

•Select 'Sinks' from the library and


drag a 'Scope' block into the model

•Drag a signal line from the output of


the Sine Wave block to the input of
the Scope block.

•Run the simulation by pressing the


'Run' button
26. SIMULINK
Best thing to do is to go through an example

2nd order, constant coefficient, linear differential equation

y  c1y  c0 y  b0f (t)

Response to a “step” command


26. SIMULINK
Get an equivalent block diagram for the system

use mouse to drag blocks into the model


window and to connect blocks with arrows

use integrators to get dy/dt and y


26. SIMULINK

add gain and summer blocks


26. SIMULINK
add the step input block
26. SIMULINK

add the output block


26. SIMULINK
Now, double click the blocks to open and set the block’s parameters

set gain value

set initial condition

set variable name

set output format to “array”


26. SIMULINK
To set the simulation parameters….

select Simulation -> Simulation Parameters

set Start and Stop time (in seconds)

set numerical integration type


26. SIMULINK
Time to run the simulation

click the “run” button to begin the simulation

when the simulation is complete, “Ready” appears at the bottom


26. SIMULINK

Simulink will automatically save a variable named “tout” to the workspace.

This variable contains the time values used in the simulation, important for variable
time integration types

Simulink also will create the output variable(s) you specified


26. SIMULINK
>>plot(tout,yoft)
graph of the step response
26. SIMULINK
Another approach to solving the 2nd order single DOF problem, is to
cast it as a 1st order 2 DOF problem

x1  y x1  x 2
x2  y x 2  bo f  c1x 2  co x1

In Matrix (or State Space) form…. x  Ax  Bu


y  Cx

 x1   0 1  0
x  A B 
x 2   co c1   bo 
uf C  1 0
26. SIMULINK
1st Order State-Space Models
26. SIMULINK
Build Model for D.E
1

Represention of DE in Block form

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)

This is the Subsystem block is


from the Subsystems library
26. SIMULINK
Creating Subsystems
STEP 2: Double click Subsystem block and create
a model in the Subsystem block

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

Output from Scope block

You might also like