Matlab Manuals
Matlab Manuals
Matlab Manuals
2222222020
Table of Contents
LAB#1..................................................................................................................................................................... 8
INTRODUCTION TO MATLAB ................................................................................................................................. 8
1.1 Introduction .......................................................................................................................................... 8
1.2 MATLAB Capabilities ............................................................................................................................. 8
1.3 Data Analysis and Visualization ............................................................................................................. 8
1.4 MATLAB Environment ........................................................................................................................... 9
1.4.1 Command Window........................................................................................................................ 9
1.4.2 Command History Window ........................................................................................................... 9
1.4.3 Workspace ................................................................................................................................... 10
1.4.4 Current Folder ............................................................................................................................. 10
1.4.5 Edit Window ................................................................................................................................ 10
1.4.6 Figure Window ............................................................................................................................ 10
1.5 MATLAB Symbols with their Operations ............................................................................................. 10
1.6 Some useful MATLAB Commands ....................................................................................................... 11
1.7 Docking and Undocking ....................................................................................................................... 11
1.8 Abort.................................................................................................................................................... 11
LAB#2................................................................................................................................................................... 12
IMPLEMENTATION OF CONSTANTS, VARIABLES AND EXPRESSIONS.................................................................. 12
2.1 Introduction ........................................................................................................................................ 12
2.2 Character Set ....................................................................................................................................... 12
2.3 Data Types ........................................................................................................................................... 12
2.3.1 Character Data Types .................................................................................................................. 12
2.3.2 Numeric Data Types .................................................................................................................... 13
2.4 Constants and Variables ...................................................................................................................... 13
2.5 Commands Related To Complex Numbers ......................................................................................... 13
2.6 Conversions of Coordinate System: .................................................................................................... 13
2.7 Character Constant: ............................................................................................................................ 14
2.7.1 Single Character Constants ......................................................................................................... 14
2.7.2 String Constants: ......................................................................................................................... 14
2.7.3 Escape Sequence Constants ........................................................................................................ 14
2.8 Variables .............................................................................................................................................. 14
MATLAB MANUALS 1
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
MATLAB MANUALS 2
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
3.15.2 Task#2.......................................................................................................................................... 30
3.15.3 Task#3.......................................................................................................................................... 31
3.15.4 Task#4.......................................................................................................................................... 31
3.15.5 Task#5.......................................................................................................................................... 33
3.15.6 Task#6.......................................................................................................................................... 34
3.15.7 Task#7.......................................................................................................................................... 35
LAB#4................................................................................................................................................................... 37
IMPLEMENTATION OF MATRICES ....................................................................................................................... 37
4.1 Introduction ........................................................................................................................................ 37
4.2 Matrix Manipulation ........................................................................................................................... 37
4.2.1 Reshaping matrices as a vector ................................................................................................... 37
4.2.2 Reshaping matrices as a differently sized matrix ........................................................................ 37
4.2.3 Expanding the matrix size ........................................................................................................... 37
4.2.4 Appending a Row/Column to a Matrix........................................................................................ 38
4.3 Deleting a Row/Column of a Matrix .................................................................................................... 38
4.4 Random Numbers Generation ............................................................................................................ 39
4.5 Using range within matrix ................................................................................................................... 40
4.6 Polynomials in Matrix Form ................................................................................................................ 40
4.7 ILLUSTRATIVE PROGRAMS .................................................................................................................. 40
4.7.1 Task#1.......................................................................................................................................... 40
4.7.2 Task#2.......................................................................................................................................... 41
4.7.3 Task#3.......................................................................................................................................... 43
4.7.4 Task#4.......................................................................................................................................... 44
4.7.5 Task#5.......................................................................................................................................... 45
LAB#5................................................................................................................................................................... 46
MANIPULATION OF POLYNOMIALS..................................................................................................................... 46
5.1 Introduction ........................................................................................................................................ 46
5.2 Entering a Polynomial ......................................................................................................................... 46
5.3 Arithmetic Operations on Polynomials ............................................................................................... 47
5.4 Useful Commands for Polynomials ..................................................................................................... 47
5.5 ILLUSTRATIVE PROGRAMS .................................................................................................................. 48
5.5.1 Task#1.......................................................................................................................................... 48
5.5.2 Task#2.......................................................................................................................................... 48
MATLAB MANUALS 3
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
5.5.3 Task#3.......................................................................................................................................... 49
5.5.4 Task#4.......................................................................................................................................... 49
5.5.5 Task#5.......................................................................................................................................... 50
5.5.6 Task#6.......................................................................................................................................... 51
5.5.7 Task#7.......................................................................................................................................... 51
5.5.8 Task#8.......................................................................................................................................... 52
LAB#6................................................................................................................................................................... 53
CONSTRUCTION OF 2-DIMENSIONAL GRAPHS IN MATLAB ................................................................................ 53
6.1 Introduction: ....................................................................................................................................... 53
6.2 List of Commands ................................................................................................................................ 53
6.3 Style Options ....................................................................................................................................... 55
6.4 ILLUSTRATIVE PROGRAMS .................................................................................................................. 56
6.4.1 Task#01........................................................................................................................................ 56
6.4.2 Task#02........................................................................................................................................ 56
6.4.3 Task#03........................................................................................................................................ 57
6.4.4 Task#04........................................................................................................................................ 58
6.4.5 Task#05........................................................................................................................................ 59
6.4.6 Task#06........................................................................................................................................ 60
6.4.7 Task#08........................................................................................................................................ 62
6.4.8 Task#09........................................................................................................................................ 63
6.4.9 Task#10........................................................................................................................................ 64
LAB#7................................................................................................................................................................... 66
CONSTRUCTION OF 3-DIMENSIONAL GRAPHS IN MATLAB ................................................................................ 66
7.1 Introduction ........................................................................................................................................ 66
7.2 List of 3D Graphic Commands ............................................................................................................. 66
7.3 ILLUSTRATIVE PROGRAMS .................................................................................................................. 67
7.3.1 Task#01........................................................................................................................................ 67
7.3.2 Task#02........................................................................................................................................ 67
7.3.3 Task#03........................................................................................................................................ 68
7.3.4 Task#04........................................................................................................................................ 69
7.3.5 Task#05........................................................................................................................................ 69
7.3.6 Task#06........................................................................................................................................ 71
LAB#8................................................................................................................................................................... 72
MATLAB MANUALS 4
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
MATLAB MANUALS 5
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
MATLAB MANUALS 6
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
MATLAB MANUALS 7
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
1 LAB#1
INTRODUCTION TO MATLAB
(BASIC CONCEPTS)
The learning objectives are:
Starting and Ending a MATLAB session.
Learn about the major components of MATLAB environment.
Learn to use Help Browser and help Command.
Know about different types of files used in MATLAB.
Know the various platforms where MATLAB can be used.
Some other useful general commands.
1.1 Introduction
MATLAB stands for MATRIX LABORATORY. A special purpose computer program optimized to
perform Engineering and Scientific calculations or it is a Technical programming language. It is started
with simple matrix manipulation and grown with the capability of solving any technical problem. It is
a proprietary programming language developed by Math-works. It provides a very extensive library of
pre-defined functions to make technical programming task easier and more efficient. It is superior on
other languages like C, C++, FORTRAN.
1.2 MATLAB Capabilities
Numerical computation
Data Access
Data Analysis and Visualization
Programming and Algorithm development
Application development and deployment
MATLAB MANUALS 8
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Similarly, commands may be deleted by selecting the command and right clicking the mouse and
selecting “Delete selection” from pop-up menu.
MATLAB MANUALS 9
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
1.4.3 Workspace
A workspace is a collection of all the variables that have been generated so far in the current MATLAB
session and shows their data type and size. The workspace information can also be obtained by typing
command at the command prompt. The “who” and “whos” command will generate list of variables
currently in the workspace. Workspace stores generated variables temporarily. The workspace will be
cleared when we closed the MATLAB. All the commands executed from command window and all the
script files executed from the command window share common workspace, so they can share all the
variables. Using these variables, a number of operations can be done such as plotting by selecting a
variable and right clicking the mouse and selecting the desired option from pop-up menu.
1.4.4 Current Folder
It contained all executed programs and save MATLAB files. In the current folder window, all the files
and folder present in the current directory will be listed. To run any file it must either be in the current
directory or on the search path. A quick way to view or change the current directory or its content is by
using the current directory field in MATLAB toolbar. For this click on “DESKTOP” on the menu bar
and check the boxes to show window.
MATLAB MANUALS 10
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
e.g. >>x=2;
It will not be executed
Used to define a range
e.g.
we want to write counting from 1 to 100 with gap 1, then >>1:1:100
It will display all numbers from 1 to 100.
: Generally,
Initial point : desired gap : final point
>>2:2:20 %TABLE OF 2
It will display.
2 4 6 8 …...20
It is typed in the beginning of a line in edit window. It create cell (highlighted
%%
rectangle) which can be executed separately / individually by using icon.
1.6 Some useful MATLAB Commands
Commands Description
clc To clear screen of command window
clf To clear figure window
who List the variables currently in the workspace
whos Same as “who” command but gives more information such as type and size
what Display all saved file on command window
clear To clear workspace
clear all To clear variables in workspace
close all To close all windows
plot To plot a graph
fprintf To print the output on the screen / command window
quit/exit To close the MATLAB session
1.7 Docking and Undocking
Docking means attaching the window to MATLAB environment. This is done by clicking the icon on
the top right corner of every window. Undocking means detaching the window from MATLAB
environment.
1.8 Abort
In order to abort a command in MATLAB hold down the control key and press “C” to generate a local
abort MATLAB.
MATLAB MANUALS 11
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
2 LAB#2
IMPLEMENTATION OF CONSTANTS, VARIABLES
AND EXPRESSIONS
The learning objectives are:
MATLAB MANUALS 12
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Constants refer to find values which donot change during the execution of a program.
Constants can be of two types:
Numeric Constants
Numeric constants are of three types. That are Integer constants, Real constants and Complex
constants. MATLAB does not differentiate between Integer and Real constants during execution.
2.5 Commands Related To Complex Numbers
Let x is defined as: 𝑥 = 𝑎 + 𝑏𝑖
Sr. # Operations Description
[theta,r]=cart2pol(x,y)
e.g. >>x=1; y=1;
Cartesian To Polar
>>[theta,r]=cart2pol(1,1)
(𝑥, 𝑦) → (𝑟, 𝜃)
>>theta=0.7854
r =1.4142
[x,y]=pol2cart(theta,r)
Polar To Cartesian e.g. >>theta=1, r=5;
(𝑟, 𝜃) → (𝑥, 𝑦) >>[x,y] = pol2cart(1,5)
>>x=2.7015 y=4.2074
MATLAB MANUALS 13
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
MATLAB MANUALS 14
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
2.9 Special Constants & Variables
Pi 3.141519
i/j √−1
Inf ∞
exp(x) Calculate 𝑒 𝑥
tand(x),cscd(x)
secd(x),cotd(x)
MATLAB MANUALS 15
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
asin(x) Compute the inverse sine of ‘x’ where ‘x’ must between -1 and 1. The function
returns an angle in radians between −𝜋⁄2 and 𝜋⁄2
acos(x) Compute the inverse cosine of ‘x’ where ‘x’ must between -1 and 1. The function
returns an angle in radians between 0 and π
atan(x) Compute the inverse tangent of ‘x’. The function returns an angle in radians
between −𝜋⁄2 and 𝜋⁄2
atan2(y,x) 𝑦
Compute the inverse tangent of value ⁄𝑥 the function returns an angle in radians
that will be between –π and π depending on signs of ‘x’ & ‘y’.
sinh(x) 𝑒 𝑥 −𝑒 −𝑥
Compute the hyperbolic sine of ’x’ which is equal to 2
cosh(x) 𝑒 𝑥 +𝑒 −𝑥
Compute the hyperbolic cosine of ’x’ which is equal to 2
tanh(x) 𝑒 𝑥 −𝑒 −𝑥
Compute the hyperbolic tangent of ’x’ which is equal to 𝑒 𝑥 +𝑒 −𝑥
asinh(x) Compute the inverse hyperbolic sine of ’x’ which is equal to ln[𝑥 + √𝑥 2 + 1]
1+𝑥
equal to ln √1−𝑥 for |x|≤1
MATLAB MANUALS 16
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
𝐀𝐫𝐞𝐚 𝐎𝐟 𝐂𝐢𝐫𝐜𝐥𝐞 = 𝛑𝐫 𝟐
Program
r = 3;
Area = pi * (r ^ 2)
Output
Area =
28.26
2.12.2 Task#2
Given two sides a=3.2 & b=4.6 of a triangle and angle 60o between these two
sides, find the length of the third side and the area of the triangle?
a=3.2;
b=6.4;
theta=60;
% Length of third side
c= sqrt(a^(2)+b^(2)-2*a*b*cos(theta))
% Area of circle in radians
Area= 0.5*a*b*sind(theta)
% Area of circle in degree
Area= 0.5*a*b*sin(theta)
Output
c =
9.4979
Area =
8.8681
Area =
-3.1213
MATLAB MANUALS 17
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
2.12.3 Task#3
Write a program to convert temperature given in °C say 35.4°C to °F?
°F= 9/5°C+32
Program
C = 35.4;
F=(9/5*C+32)
Output
F =
95.7200
2.12.4 Task4#
Write MATLAB statement and calculate sum of series for x=1.5?
𝒙𝟐 𝒙𝟒 𝒙𝟔 𝒙𝟖
𝒔=𝟏− + − +
𝟐! 𝟒! 𝟔! 𝟖!
Program
x=1.5;
s= 1-(x^2/factorial(2))+(x^4/factorial(4))-(x^6/factorial(6))+(x^8/factorial(8))
Output
s=
0.0708
2.12.5 Task#5
Evaluate the following assignment statements.
Program
MATLAB MANUALS 18
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
x=1/2;
r= log(x^2+x+1)
x=1;
s= log(x^2+x+1)
%% x/(x^2+1)(sinx)
x=pi/4;
t= (x./(x.^2+1).*sin(x))
x=pi/2;
u= (x./(x.^2+1).*sin(x))
Output
q =
14.3480
r =
0.5596
s =
1.0986
t =
0.3435
u =
0.4530
2.12.6 Task#6
Evaluate the given number for ‘x’ from 1 to 2 in steps of 0.1.
𝟏 𝒙𝟑
𝒚= + 𝟒
𝒙 𝒙 + 𝟓𝒙 𝐬𝐢𝐧 𝒙
Program
x=1:0.1:2;
y= (1./x)+((x.^3))./((x.^4)+(5.*x.*sin(x)))
Output
Columns 1 through 6
Columns 7 through 11
MATLAB MANUALS 19
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
2.12.7 Task#7
Write assignment statements to evaluate the following equations:
𝑽𝑰 𝐜𝐨𝐬 𝜽
(C) 𝑬𝒇𝒇𝒊𝒄𝒊𝒆𝒏𝒄𝒚 = 𝒇𝒐𝒓 𝑽 = 𝟐𝟓𝟎 , 𝑰 = 𝟓 , 𝑹 = 𝟐 , 𝐜𝐨𝐬 𝜽 = 𝟎. 𝟖 , 𝝎𝒄 = 𝟐𝟎
𝑽𝑰 𝐜𝐨𝐬 𝜽+𝑰𝟐 𝑹+𝝎𝒄
Program
%% Volume = pi*r^2*h
r=2;
h=3;
v= pi*(r^2)*h
%% Power= 2piNT/60
N= 1000;
T= 10;
p= (2*pi*N*T)/60
%% Efficiency= VIcos(theta)/VIcos(theta)+I^2R+Wc
V=250;
I=5;
R=2;
theta=0.8;
Wc=20;
e= V*I*cos(theta)/V*I*cos(theta)+I^2*R+wrightOmega(Wc)
Output
v =
37.6991
p =
1.0472e+03
e =
79.2926
MATLAB MANUALS 20
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
2.12.8 Task#8
For an electrical circuit with an inductance l=0.01mh and resistance r=180 ohms the damped
natural frequency of oscillations is:
𝟏 𝑹𝟐
𝑭𝒓𝒆𝒒𝒖𝒆𝒏𝒄𝒚 = √ −
𝑳𝑪 𝟒𝑪𝟐
Write a program to calculate the frequency for different values of ‘c’ varying from 0.1 to 1 in step
of 0.1.
Program
L=0.01;
R=180;
C=0.1:0.1:1;
F=sqrt((1./L.*C)+(R.^2)/4.*(C.^2))
Output
F =
Columns 1 through 9
9.5394 18.5472 27.5500 36.5513 45.5522 54.5527 63.5531 72.5534
81.5537
Column 10
90.5539
MATLAB MANUALS 21
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
3 LAB#3
IMPLEMENTATION OF VECTORS
The learning objectives are:
Knowledge of scalar, vectors and matrices and basic operations such as product and transpose
Useful commands/functions related to vectors and matrices
3.1 Introduction
The matrix notation usually simplifies the complex mathematical expressions /equations and makes
solution of problems much easier to handle and manipulate. In MATLAB, a matrix is a rectangular
array of real or complex numbers. Matrices with only one row or with only one column are called row
and column vectors, respectively. A matrix having only one element is called a scalar.
Although other higher programming languages work with one number at a time, in MATLAB it is
possible to work with complete matrix simultaneously. This feature is very important as it removes the
un-necessary loops and repetition of same statements. The program, therefore, becomes short, concise
and easily understandable. In MATLAB, matrix is chosen as a basic data element. All variables when
used as a single data element are treated as single element matrix that is a matrix with one row and one
column.
3.2 Arrays
An array is a list of numbers arranged in rows and/or columns. A one-dimensional array is a row or a
column of numbers and a two dimensional array has a set of numbers arranged in rows and columns.
An array operation is performed element by element.
MATLAB MANUALS 22
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
3.4.3 Scalar
A scalar does not need any square brackets, for example a scalar 𝑥 = 10 can be entered as:
𝑥 = 10 ;
𝑉𝑎𝑟𝑖𝑎𝑏𝑙𝑒_𝑛𝑎𝑚𝑒 = 𝐾: 𝐿: 𝑀
A row vector can also be created by using linepsace command. The syntax is given as follows:
𝒍𝒊𝒏𝒔𝒑𝒂𝒄𝒆 (𝑥𝑎 , 𝑥𝑏 , 𝒏)
It generates a linearly space vector of length ‘n’ that is ‘n’ equally spaced points between 𝑥𝑎 and 𝑥𝑏 . e.g. 𝐴 =
𝑙𝑖𝑛𝑠𝑝𝑎𝑐𝑒(0,10,5)
When executed, produces a vector having 5 equally spaced elements between the limits 0 and 10 given as follows:
𝐴 = [0 2.5 5.0 7.5 10.0]
size(A) >>size(A)
Returns a row vector [m,n], where m and
or >>ans = 1 4
n are the size mxn of the array A
[m,n]=size(A) (means 1 row and 4 columns)
MATLAB MANUALS 23
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
>>V=[3 2 1];
>>A=diag(V)
When ‘V’ is a vector, creates a square
>>A =
diag(V) matrix with the elements of ‘V’ in
3 0 0
diagonals.
0 2 0
0 0 1
>>x=[5 -3 10 -10]
It lists the elements of the vector ‘x’ in
sort(x,’mole’) >>a=sort(x)
ascending or descending order.
sort(x,’ascend’) >>a=[-10 -3 5 10]
If we only write sort(x), it will sort the
sort(x,’descend’) >>sort(x,’descend’)
array in ascending order automatically.
>>b=[10 5 -3 -10]
3.8 Built-In Functions for Analyzing Arrays
Some of the many built-in functions available in MATLAB for analyzing arrays are listed below:
>>ans = 14
>>c=max(A)
>>c=18
n=7
min(A) The same as max(A), but for the smallest element >>A=[3 7 2 16];
[d,n]=min(A) The same as [d,n]= max(A) but for the smallest >>min(A)
element
>>ans=2
sum(A) If ‘A’ is a vector, return the sum of the element >>A=[3 7 2 16];
of the vector
>>sum(A)
>>ans=28
MATLAB MANUALS 24
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
median(A) If ‘A’ is a vector, return the median value of the >>A=[3 7 2 16];
element of vector
>>median(A)
>>ans=5
>>ans=6.3770
>>det(A)
>>ans=-2
dot(A,B) Calculates the scalar (dot) product of two vectors >>A=[5 6 7];
A & B. The vector can each be row or column
vectors >B=[4 3 2];
>>dot(a,b)
>>ans=52
cross(A,B) Calculates the cross product of two vectors A & >>A=[5 6 7];
B (AxB). The two vectors must have three
elements. >B=[4 3 2];
>>cross(a,b)
>>ans=-9 18 -9
3.9 Matrix
A matrix is a two dimensional array which has n-number of rows and columns. A matrix is entered
row-wise with consecutive elements of a row separated by a space or a comma, and the columns are
separated by semi-colons or carriage returns. The entire matrix is enclosed with in square brackets. The
elements of the matrix may be real numbers or complex numbers. e.g.
To enter the matrix
1 3 −4
𝐴=[ ]
0 −2 8
In MATLAB input command is:
𝐴 = [1 3 −4 ; 0 −2 8]
MATLAB MANUALS 25
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
𝐴(: , 𝑛) Refers to the elements in all the rows of the column ‘n’ of the matrix ‘A’.
𝐴(𝑚, : ) Refers to the elements in all the columns of the row ‘m’ of the matrix ‘A’.
𝐴(: , 𝑚: 𝑛) Refers to the element in all the rows between column ‘m’ and ‘n’ of the matrix
’A’.
𝐴(𝑚: 𝑛, : ) Refers to the elements in all the columns between row ‘m’ and ‘n’ of matrix
‘A’
𝐴(𝑚: 𝑛, 𝑝: 𝑞) Refers to the elements in rows ‘m’ through ‘n’ and columns ‘p’ through ‘q’
of matrix ‘A’.
ARITHMETIC OPERATORS
+ Addition + Addition
- Subtractions - Subtractions
MATLAB MANUALS 26
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
>>det(A)
>>ans=4
1 0
2 4
1. Zeros (m,n)
It returns a rectangular 𝑚 × 𝑛 matrix of all zeros.
2. Ones (m,n)
It returns a rectangular 𝑚 × 𝑛 matrix of all ones.
3. eye (m,n)
It returns a rectangular 𝑚 × 𝑛 matrix with ones on the main diagonal and zeros elsewhere.
MATLAB MANUALS 27
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
%% a) P*Q
P=[1,-2,5];
Q=[2;4;8];
P*Q
%% b) Q*P
P=[1,-2,5];
Q=[2;4;8];
Q*P
%% c) PT*QT
P=[1,-2,5];
Q=[2;4;8];
transpose(P)*transpose(Q)
MATLAB MANUALS 28
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Q=[2;4;8];
max(P)
max(Q)
min(P)
min(Q)
ans =
34
ans =
2 -4 10
4 -8 20
8 -16 40
ans =
2 4 8
-4 -8 -16
10 20 40
ans =
4
ans =
14
ans =
1.3333
ans =
4.6667
ans =
3
ans =
3
ans =
5
ans =
8
ans =
-2
ans =
2
MATLAB MANUALS 29
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
ans =
-10
ans =
64
ans =
-2 1 5
ans =
2
4
8
3.15.2 Task#2
𝟐 −𝟒 𝟔 −𝟖
Given the matrix 𝑨 = [𝟏 𝟑 𝟓 𝟕] Write MATLAB statement to obtain:
𝟐 𝟏𝟐 𝟑𝟎 𝟓𝟔
a) All the elements of all rows but first column.
b) All the elements of first row but all columns.
c) Elements in the 2nd row & 3rd column.
Program
% a) All the elements of all rows but first column.
b =
2 -4 6 -8
c =
5
MATLAB MANUALS 30
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
3.15.3 Task#3
Generate the following 3*3 matrices of common use with the help of MATLAB functions:
a) Unity or Identity matrix.
b) Null matrix.
c) Matrix with all elements equal to one where P=3 & Q=4.
Program
% Matrix with all elements equal to one where P=3 & Q=4.
ones(3,4)
Output
ans =
1 0 0
0 1 0
0 0 1
ans =
0 0 0
0 0 0
0 0 0
ans =
1 1 1 1
1 1 1 1
1 1 1 1
3.15.4 Task#4
For the following matrices, find:
a) Determinants.
b) The inverse of each, if they exist & the corresponding product AA-1, BB-1
2 4
A= [ ]
8 −1
3 0 −2
B= [−1 1 2]
0 1 −2
1 2 3
C= [0 −1 1]
1 0 1
MATLAB MANUALS 31
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
0 2 0
D= [3 −3 4]
0 2 6
Program
% Determinants of Matrices
A=[2,4; 8,-1];
B=[3,0,-2; -1,1,2; 0,1,-2];
C=[1,2,3; 0,-1,1; 1,0,1];
D=[0,2,0; 3,-3,4; 0,2,6];
det(A)
det(B)
det(C)
det(D)
% Inverse of Matrices
A=[2,4; 8,-1];
B=[3,0,-2; -1,1,2; 0,1,-2];
C=[1,2,3; 0,-1,1; 1,0,1];
D=[0,2,0; 3,-3,4; 0,2,6];
inv(A)
inv(B)
inv(C)
inv(D)
% Corresponding product AA-1, BB-1
A=[2,4; 8,-1];
B=[3,0,-2; -1,1,2; 0,1,-2];
C=[1,2,3; 0,-1,1; 1,0,1];
D=[0,2,0; 3,-3,4; 0,2,6];
A*inv(A)
B*inv(B)
C*inv(C)
D*inv(D)
Output
ans =
-34
ans =
-10
ans =
4
ans =
-36
ans =
0.0294 0.1176
0.2353 -0.0588
MATLAB MANUALS 32
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
ans =
0.4000 0.2000 -0.2000
0.2000 0.6000 0.4000
0.1000 0.3000 -0.3000
ans =
ans =
0.7222 0.3333 -0.2222
0.5000 0 0
-0.1667 0 0.1667
ans =
1 0
0 1
ans =
1 0 0
0 1 0
0 0 1
ans =
1 0 0
0 1 0
0 0 1
ans =
1.0000 0 0
-0.0000 1.0000 0
0 0 1.0000
3.15.5 Task#5
Determine the ranks of the following matrices:
𝟒 𝟑
a) L =[𝟕 𝟐]
𝟒 𝟎
𝟑 𝟓 𝟎 𝟗
b) M = [ ]
𝟐 𝟑 𝟔 𝟒
𝟏 𝟐 𝟑
c) N= [𝟒 𝟓 𝟔]
𝟕 𝟖 𝟗
MATLAB MANUALS 33
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Program
M=[3,5,0,9; 2,3,6,4];
b=rank(M)
N=[1,2,3; 4,5,6; 7,8,9];
c=rank(N)
Output
a =
2
b =
2
c =
2
3.15.6 Task#6
Obtain the following products:
a) AB
b) BA
c) ATA
d) BTB
For the matrices given below:
𝟐 𝟒
−𝟏 𝟏 𝟑
A=[ ] , B=[𝟔 𝟖]
𝟒 𝟓 𝟔
𝟏𝟎 𝟏𝟐
Program
A=[-1 2 3; 4 5 6];
B=[2 4; 6 8; 10 12];
size(A)
size(B)
A*B
B*A
A'*A
B'*B
Output
ans =
2 3
ans =
3 2
MATLAB MANUALS 34
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
ans =
40 48
98 128
ans =
14 24 30
26 52 66
38 80 102
ans =
17 18 21
18 29 36
21 36 45
ans =
140 176
176 224
3.15.7 Task#7
Evaluate using array operations:
a) A+B
b) A-B
c) A^3 & B^4
d) A/B
𝟓 −𝟖 𝟏𝟎 −𝟐
A= [𝟎 𝟒 𝟑 −𝟒]
𝟐 𝟒 𝟔 𝟖
𝟑 −𝟑 −𝟔 𝟓
B= [𝟖 𝟎 𝟓 𝟒]
𝟎 𝟒 𝟑 𝟐
Program
ans =
8 -11 4 3
8 4 8 0
2 8 9 10
MATLAB MANUALS 35
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
ans =
2 -5 16 -7
-8 4 -2 -8
2 0 3 6
ans =
125 -512 1000 -8
0 64 27 -64
8 64 216 512
ans =
81 81 1296 625
4096 0 625 256
0 256 81 16
ans =
1.6667 2.6667 -1.6667 -0.4000
0 Inf 0.6000 -1.0000
Inf 1.0000 2.0000 4.0000
MATLAB MANUALS 36
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
4 LAB#4
IMPLEMENTATION OF MATRICES
The learning objectives are:
𝑏 = 𝐴(: )
Matrix A will be stored column wise in vector b i.e. first column is stored first, then second column and
so on.
4.2.2 Reshaping matrices as a differently sized matrix
If a given matrix A is a 𝑝 × 𝑞 matrix, it can be reshaped in to a new matrix 𝑚 × 𝑛 as long as total
elements of the two matrices are same i.e.
𝑝×𝑞 =𝑚×𝑛
𝐵 = 𝑟𝑒𝑠ℎ𝑎𝑝𝑒(𝐴, 𝑚, 𝑛)
When executed, this command will reshape the matrix A in to matrix B of size 𝑚 × 𝑛. The elements
of the matrix B are taken column wise from matrix A.
Commands are:
MATLAB MANUALS 37
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
1. Appending Column
𝐴 = [𝐴 𝑥] 𝑤ℎ𝑒𝑟𝑒 𝑥 = [𝑎; 𝑏; 𝑐]
2. Appending Row
𝐴 = [𝐴 ; 𝑦] 𝑤ℎ𝑒𝑟𝑒 𝑦 = [𝑎 𝑏 𝑐]
Semicolon is used to append row. In appending rows and columns, take care of dimensions of matrix.
𝑨(𝒊, : ) = [ ]
𝑨(: , 𝒋) = [ ]
𝑨(𝒊, 𝒋) = [ ]
This type of command will give error, because single element cannot be deleted from a matrix.
𝑪(𝒂𝒊𝒋 : 𝒃𝒊𝒋 , : ) = [ ]
MATLAB MANUALS 38
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
MATLAB has two commands that can be used to assign random numbers to variables
>>ans=0.9501
0.4565
0.0185
0.8214
rand(n) Generates an nxn matrix with random numbers between >>b=rand(3)
0 and 1.
>>b=
MATLAB MANUALS 39
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
𝐴 = [𝑘1 : 𝑙1 : 𝑚1 ; 𝑘2 : 𝑙2 : 𝑚2 ; 𝑘3 : 𝑙3 : 𝑚3 ; … ]
Or
Keep ‘n’ same for all rows. It will generate same number of elements in each row. The initial and final
points can be taken any value but initial point must be less than the final point.
It returns the coefficients of the characteristics polynomial ‘p’ of the matrix ‘A’ i.e. the coefficient of
the determinant of matrix [𝑥𝐼 − 𝐴], where I is the identity matrix. The syntax is given as:
𝒑 = 𝒑𝒐𝒍𝒚(𝑨)
When executed gives the co-efficient of the polynomial ‘p’ in descending power of ‘x’ as:
p=[ 1 −5 4]
eig(A):
It returns the eigen values of matrix ‘A’ where ‘A’ is any given matrix.
[𝑽, 𝒙] =eig(A):
It returns the eigen vectors ‘V’ and eigen values shown on the main diagonal of the
matrix ‘x’.
MATLAB MANUALS 40
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Q1 =
6 7 8 9
9 10 11 12
Q2 =
5 6
8 9
11 12
Q3 =
7 8
10 11
Q4 =
3 4 5 6
6 800 8 9
9 10 11 12
4.7.2 Task#2
𝟑 𝟒 𝟓 𝟏
Given the matrix P: P = [𝟓 𝟔 𝟕 𝟐]
𝟕 𝟖 𝟗 𝟑
a) Reshape this matrix as a:
Column vector.
(4*3) matrix.
(6*2) matrix
𝟎
b) Given a column vector, x = [𝟏] & a row vector, y = [𝟎 𝟐 𝟑 𝟒] , append these
𝟐
column/row vector to the matrix P, given above.
MATLAB MANUALS 41
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Program
%%
p=[3 4 5 1; 5 6 7 2; 7 8 9 3];
a=p(:)
b= reshape(p,4,3)
c= reshape(p,6,2)
%%
p=[3 4 5 1; 5 6 7 2; 7 8 9 3];
x=[0;1;2];
y=[0,2,3,4];
p1=[p x]
%%
p=[3 4 5 1; 5 6 7 2; 7 8 9 3];
y=[0,2,3,4];
p2=[p;y]
Output
a =
3
5
7
4
6
8
5
7
9
1
2
3
b =
3 6 9
5 8 1
7 5 2
4 7 3
c =
3 5
5 7
7 9
4 1
6 2
8 3
MATLAB MANUALS 42
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
p1=
3 4 5 1 0
5 6 7 2 1
7 8 9 3 2
p2 =
3 4 5 1
5 6 7 2
7 8 9 3
0 2 3 4
4.7.3 Task#3
Consider matrix A is given by:
𝟐 𝟓 𝟔
A = [𝟑 𝟒 𝟏𝟎]
𝟕 𝟏𝟏 𝟖
Show the use of the following MATLAB command:
a) Diagonal (A), A is a matrix.
b) Diagonal (A, K), A is a matrix.
c) Polynomial (A).
d) Eigen (A).
Program
ans =
2
4
8
ans =
6
ans =
1.0000 -14.0000 -111.0000 -104.0000
ans =
19.8545
-1.1022
-4.7523
MATLAB MANUALS 43
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
4.7.4 Task#4
Express the following sets of algebraic equations in matrix form, Ay=b
𝒙+𝒚−𝒛 =𝟐
−𝒙 + 𝟑𝒚 − 𝒛 = 𝟐
𝟑𝒙 + 𝟓𝒚 − 𝟐𝒛 = 𝟐
For this set of equations;
a) Find the inverse of the matrix, if it exists.
b) Obtain the solution of the variables x, y & z.
c) Find the Eigen values and Eigen vectors of matrix A.
d) Find the trace of matrix A.
e) Find the transpose of matrix A.
Program
A=[1 1 1;-1 3 -1;4 -4 0];
B=[4;4;0];
X=inv(A)*B
[v x]=eig(A)
trace(A)
transpose(A) % second method for transpose is A’
Output
X =
2
2
0
v =
-0.0000 0.7071 -0.3487
0.7071 0.7071 0.1162
-0.7071 0.0000 0.9300
x =
4.0000 0 0
0 2.0000 0
0 0 -2.0000
ans =
4
ans =
1 -1 4
1 3 -4
1 -1 0
MATLAB MANUALS 44
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
4.7.5 Task#5
Create a 4*4 matrix of random numbers, multiply all the elements of matrix by 10 & then round
off all the elements to integers using appropriate commands.
Program
a=rand(4)
b=10*a
round_off=round (b)
Output
a=
0.8147 0.6324 0.9575 0.9572
0.9058 0.0975 0.9649 0.4854
0.1270 0.2785 0.1576 0.8003
0.9134 0.5469 0.9706 0.1419
b =
8.1472 6.3236 9.5751 9.5717
9.0579 0.9754 9.6489 4.8538
1.2699 2.7850 1.5761 8.0028
9.1338 5.4688 9.7059 1.4189
round_off =
8 6 10 10
9 1 10 5
1 3 2 8
9 5 10 1
MATLAB MANUALS 45
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
5 LAB#5
MANIPULATION OF POLYNOMIALS
The learning objectives are:
MATLAB can interrupt a vector of length (n+1) as an nth order polynomial. Thus, if there are missing
terms, zeroes must be entered in the appropriate places in the vector.
e.g. 𝑦 = 𝑥 3 + 1
In MATLAB: 𝑦 = [1 0 0 1] or 𝑦 = [1,0,0,1]
Two zeroes have been included in a vector to account for missing powers of x, i.e. 𝑥 2 and 𝑥.
MATLAB MANUALS 46
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Z = Dividend vector,
Division of Two [𝑥, 𝑟] y = Divisor vector,
Polynomials = 𝑑𝑒𝑐𝑜𝑛𝑣(𝑧, 𝑦) x = Vector of quotients obtained,
r = vectors of remainders obtained.
5.4 Useful Commands for Polynomials
List Of Commands Description
𝑝𝑜𝑙𝑦𝑣𝑎𝑙(𝑝, 𝑥) Evaluate polynomials at ‘x’
𝑟𝑜𝑜𝑡𝑠(𝑝) Computes the roots of polynomial
𝑐𝑜𝑛𝑣(𝑝, 𝑞) Multiplication of two polynomials
𝑑𝑒𝑐𝑜𝑛𝑣(𝑝, 𝑞) Division of two polynomials
𝑝𝑜𝑙𝑦(𝑟) Converts given roots to polynomial
𝑝𝑜𝑙𝑦𝑑𝑒𝑟(𝑝) Differentiate a polynomial
Integrates polynomial analytically, ‘c’ is constant of
𝑝𝑜𝑙𝑦𝑖𝑛𝑡(𝑝, 𝑐) integration. If it is not mentioned in command, 1 is
taken by default at place of ‘c’.
𝑝𝑜𝑙𝑦𝑓𝑖𝑡(𝑥, 𝑦, 𝑘) Fits a polynomial to given data
MATLAB MANUALS 47
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
V1 =
-3.0000 39.2500 -3.0000 +32.0000i
V2 =
5.0000 21.2500 -11.0000 +16.0000i
V3 =
-2.0000 40.2500 -2.0000 +32.0000i
5.5.2 Task#2
Find the Roots of the following Polynomials?
P1 = x2 + 3x +2.
P2 = x4 + 4x3 + 9x +2.
P3 = x5 + 1.
P4 = x3 + 3x2 + 4x + 1.
Program
P1=[1 3 2];
P2=[1 4 0 9 2];
P3=[1 0 0 0 0 1];
P4=[1 3 4 1];
r1=roots(P1)
r2=roots(P2)
r3=roots(P3)
r4=roots(P4)
Output
r1 = -2
-1
MATLAB MANUALS 48
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
r2 = -4.4347
0.3263 + 1.4012i
0.3263 - 1.4012i
-0.2179
r3 = -1.0000
-0.3090 + 0.9511i
-0.3090 - 0.9511i
0.8090 + 0.5878i
0.8090 - 0.5878i
r4 = -1.3412 + 1.1615i
-1.3412 - 1.1615i
-0.3177
5.5.3 Task#3
Multiply the following Polynomials?
P1 = x + 3.
P2 = x + 6.
P3 = x2 + 4x +6.
Program
P1=[1 3];
P2=[1 6];
P3=[1 4 6];
P4=conv(P1,P2)
P5=conv(P3,P4)
Output:
P4 =
1 9 18
P5 =
1 13 60 126 108
5.5.4 Task#4
Divide Polynomial P by q?
a) P = x3 + 4x +10. Q = x3 + 3x2 + 4x + 2.
b) P = 5x2 + 8x + 2. Q = x2 + x + 2.
c) P = 2x2 + 3x + 1. Q =x2 + x – 1.
Program
P1=[1 0 4 10];
Q1=[1 3 4 2];
[z1,r1]=deconv(P1,Q1) % z=Quotient , r1=Remainder, P/Q (P divided by Q)
P2=[5 8 2];
Q2=[1 1 2];
[z2,r2]=deconv(P2,Q2)
P3=[2 3 1];
Q3=[1 1 -1];
[z3,r3]=deconv(P3,Q3)
MATLAB MANUALS 49
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Output
z1 =
1
r1 =
0 -3 0 8
z2 =
5
r2 =
0 3 -8
z3 =
2
r3 =
0 1 3
5.5.5 Task#5
Roots of Polynomial are given below find the Corresponding Polynomials?
a) r1 = 2, 4.
b) r2 = -2, -4.
c) r3 = -2, 4.
d) r4 = -2, 4, 6.
Program
r2 = [-2,-4];
P2 = poly(r2)
r3 = [-2;4];
P3 = poly(r3)
r4 = [-2;4;6];
P4 = poly(r4)
Output
P1 =
1 -6 8
P2 =
1 6 8
P3 =
1 -2 -8
MATLAB MANUALS 50
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
P4 =
1 -8 4 48
5.5.6 Task#6
Find Polynomial of Degree 5 for a given Data, for x=12?
X: 2 5 7 9 11 13
Program
5.5.7 Task#7
Evaluate the Derivative and Integral of the following Polynomials?
P1 = x4 + 4x3 + 10x2 + 20x + 15, c = 1.
P2 = x3 + x + 10, c = 3.
P3 = x + 5, c = -3.
Program
P1=[1 4 10 20 15];
c1=1;
P2=[1 0 1 10];
c2=2;
P3=[1 5];
c3=-3;
D1=polyder(P1) %Derivative
D2=polyder(P2)
D3=polyder(P3)
I1=polyint(P1,c1) %Integration
I2=polyint(P2,c2)
I3=polyint(P3,c3)
MATLAB MANUALS 51
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Output
D1 =
4 12 20 20
D2 =
3 0 1
D3 =
1
I1 =
0.2000 1.0000 3.3333 10.0000 15.0000
1.0000
I2 =
0.2500 0 0.5000 10.0000 2.0000
I3 =
0.5000 5.0000 -3.0000
5.5.8 Task#8
Express the following system of linear equations into Matrix form and obtain the solution of the
variables x, y, z.
𝒙+𝒚−𝒛 =𝟐
−𝒙 + 𝟑𝒚 − 𝒛 = 𝟐
𝟑𝒙 + 𝟓𝒚 − 𝟐𝒛 = 𝟐
Program
A= [1 1 1; -1 3 -1; 4 -4 0];
B= [4; 4; 0];
X= inv(A)*B
Output
X =
2
2
0
MATLAB MANUALS 52
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
6 LAB#6
CONSTRUCTION OF 2-DIMENSIONAL GRAPHS IN
MATLAB
The learning objectives are:
Vector data can be visualized with 2-D plotting functions such as line, area, bar and pie charts, direction
and the velocity plots, histograms, polygons and surfaces, scatter or bubble plots and animations.
MATLAB provides functions for visualizing 2-D matrices. In MATLAB, one can specify plot
characteristics, such as viewing angle, perspective, lighting effect, light source, location and
transparency.
6.2 List of Commands
1. General Graphics Command:
or
MATLAB MANUALS 53
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
axis tight
r=number of rows
c=number of columns
l=location of subplot on
figure window
MATLAB MANUALS 54
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
𝑠𝑒𝑚𝑖 𝑙𝑜𝑔 𝑥 (𝑥, 𝑦) Plot with logarithmic scale x-axis and linear scale y-axis
𝑠𝑒𝑚𝑖 𝑙𝑜𝑔 𝑦 (𝑥, 𝑦) Plot with linear scale x-axis and logarithmic scale y-axis
𝑎𝑟𝑒𝑎(𝑥, 𝑦) Same as ‘plot’ command except area under curve is filled with color
w = white k = black
MATLAB MANUALS 55
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
x=-10:1:10;
y=x.^3+2*x.^2-5;
plot (x,y)
xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('2D Graph');
gtext ('y=x^3+2*x^2-5');
grid on
Output
_____________________________________________________________
6.4.2 Task#02
Write a program to illustrate the use of area command with specified limits, for plot of function
𝒚 = 𝐜𝐨𝐬 𝒙 for 𝒙 = 𝟎 𝒕𝒐 𝝅 with step size of 0.02?
Program
x=0:0.02:2*pi;
y=cos(x);
area (x,y)
xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('Graphing s single plot with filled area using Area Command');
gtext ('Filled Area');
MATLAB MANUALS 56
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Output
6.4.3 Task#03
Write a program to draw the curves for functions in a single figure window using single plot
command. Illustrate the use of different styles of curves which can be drawn using plot command?
𝒚𝟏 = 𝐬𝐢𝐧 𝒙
𝒚𝟐 = 𝐬𝐢𝐧(𝒙 − 𝟎. 𝟑𝟓)
𝒚𝟑 = 𝐬𝐢𝐧(𝒙 − 𝟎. 𝟓𝟓)
𝒚𝟒 = 𝐬𝐢𝐧(𝒙 − 𝟎. 𝟖𝟓)
Program
x=0:pi/10:2*pi;
y1=sin(x);
y2=sin(x-0.35);
y3=sin(x-0.55);
y4=sin(x-0.85);
plot (x,y1,'r-o' , x,y2,'b-o' , x,y3,'c-o' , x,y4,'k-o','linewidth',2)
xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('Graphing multiple plotsin a single figure window using plot
command');
legend (‘y1=sin(x)’,’y2=sin(x-0.35)’,’y3=sin(x-0.55’),’y4=sin(x-0.85)’)
grid on;
axis tight
MATLAB MANUALS 57
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Output
6.4.4 Task#04
Write a program to draw the curves for function
𝒚 = 𝟐𝟎𝟎 𝐬𝐢𝐧 𝒙 ∗ 𝒆−𝟎.𝟓𝒙
𝒚 = 𝟎. 𝟖 𝐬𝐢𝐧 𝟏𝟎𝒙 ∗ 𝒆−𝟎.𝟓𝒙
Illustrate how the “Legend” command is used to indicate the different styles used for the different
curves plotted on same graph?
Program
x=0:0.01:100;
y1=200*exp(-0.5*x).*sin(x);
y2=0.8*exp(-0.5*x).*sin(10*x);
plot (x,y1,'b',x,y2,'r')
xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('Graphing multiple plots using plot command');
legend ('y1=200*exp(-0.5*x).*sin(x)','y2=0.8*exp(-0.5*x).*sin(10*x)');
grid on
axis tight
MATLAB MANUALS 58
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Output
6.4.5 Task#05
Write a program to draw the curves for functions in a single figure window using using Hold
and Plot Command?
𝒚𝟏 = 𝐬𝐢𝐧 𝒙
𝒚𝟐 = 𝐬𝐢𝐧(𝒙 − 𝟎. 𝟑𝟓)
𝒚𝟑 = 𝐬𝐢𝐧(𝒙 − 𝟎. 𝟓𝟓)
𝒚𝟒 = 𝐬𝐢𝐧(𝒙 − 𝟎. 𝟖𝟓)
Program
x=0:pi/10:2*pi;
y1=sin(x);
plot (x,y1, 'r-.o','linewidth',2)
pause (2)
hold on
y2=sin(x-0.35);
plot (x,y2,'b-.o','linewidth',2)
pause (2)
y3=sin(x-0.55);
plot (x,y3,'c-.o','linewidt',2)
pause (2)
y4=sin(x-0.85);
plot (x,y4,'k-.o','linewidth',2)
pause (2)
hold off
MATLAB MANUALS 59
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
xlabel ('X-Axis');
ylabel ('Y-Axis');
title (‘Graphing multiple curves using Hold Command’);
grid on
axis tight
Output
6.4.6 Task#06
Write a program to draw the curves for functions in a single figure window using Line
Command?
𝒚𝟏 = 𝐬𝐢𝐧 𝒙
𝒚𝟐 = 𝐬𝐢𝐧(𝒙 − 𝟎. 𝟑𝟓)
𝒚𝟑 = 𝐬𝐢𝐧(𝒙 − 𝟎. 𝟓𝟓)
𝒚𝟒 = 𝐬𝐢𝐧(𝒙 − 𝟎. 𝟖𝟓)
Program
x=0:pi/10:2*pi;
y1=sin(x);
y2=sin(x-0.35);
y3=sin(x-0.55);
y4=sin(x-0.85);
plot(x,y2, 'b-box','linewidth',2)
pause (2)
plot(x,y3, 'g-*','linewidth',2)
MATLAB MANUALS 60
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
pause (2)
plot(x,y4, 'k-d','linewidth',2)
pause (2)
xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('Graphing multiple plots using Line Command');
legend (‘y1=sin(x)’,’y2=sin(x-0.35)’,’y3=sin(x-0.55’),’y4=sin(x-0.85)');
grid on
axis tight
Output
Task#07
Divide the Figure window into four sub-windows and plot the following functions?
Plot V versus I where V=4I and I=1,2,3,4 on the upper left sub-window.
Plot y versus x where 𝒚 = 𝒙𝟐 and x=1,2,3,4 on the upper right sub-window.
𝝅
For t=𝟎: 𝟐𝝅 in steps of t=𝟔𝟎. Plot 𝐬𝐢𝐧 𝒕 versus t on the lower left window
𝝅
For t=0:𝟑𝟎 : 𝟐𝝅. Plot 𝐜𝐨𝐬 𝒕 versus t on the lower right window.
Program:
I=1:1:4;
V=4*I;
subplot (2,2,1)
plot(I,V)
title('V Versus I');
x=1:1:4;
y=x.^2;
subplot (2,2,2)
plot(x,y)
MATLAB MANUALS 61
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
t=0:pi/60:2*pi;
Y=sin(t);
subplot (2,2,3)
plot(t,Y)
title('t Versus Sint');
t=0:pi/60:2*pi;
Y1=cos(t);
subplot (2,2,4)
plot(t,Y1)
title('t Versus Cost');
Output
6.4.7 Task#08
Plot the following functions on the polar plot:
−𝝅 𝝅
𝒇(𝜽) = 𝐬𝐢𝐧 𝟒𝜽 , 𝟐 < 𝜽 < 𝟐 , Where θ is in radians?
Program
theta=-pi/2:pi/40:pi/2;
f=sin(4*theta);
polar (theta,f,'r-')
title ('Graphing using Polar Function')
MATLAB MANUALS 62
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Output
6.4.8 Task#09
a) Draw the stairs plot to show the function 𝒚 = 𝒙𝟐 where −𝟐 ≤ 𝒙 ≤ 𝟐
b) Draw the stairs plot for the following data:
X=[0 2 3 4 5 7]
Y=[5 -1 8 4 7 3]
Program
%%
X=-2:0.1:2;
Y=X.*X;
stairs(X,Y,'c','linewidth',2) % c is for cyan color
xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('Graphing stairs plot using stairs Command');
grid on
%%
X=[0 2 3 4 5 7];
Y=[5 -1 8 4 7 3];
stairs(X,Y,'*-','linewidth',2)
xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('Graphing stairs plot using stairs Command');
grid on
MATLAB MANUALS 63
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Output
3.5
2.5
Y-Axis
1.5
0.5
0
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
X-Axis
4
Y-Axis
-1
0 1 2 3 4 5 6 7
X-Axis
6.4.9 Task#10
Draw the stem plot for the following data:
X=[0 1 2 3 4 5 6]
Y=[3 -1 6 -4 5 2 3]
Program
X=[0 1 2 3 4 5 6];
Y=[3 -1 6 -4 5 2 3];
stem(X,Y,'k','linewidth',2.5)
xlabel ('X-Axis');
ylabel ('Y-Axis');
title ('Graphing stairs plot using stairs Command');
grid on
MATLAB MANUALS 64
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Output
2
Y-Axis
-1
-2
-3
-4
0 1 2 3 4 5 6
X-Axis
MATLAB MANUALS 65
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
7 LAB#7
CONSTRUCTION OF 3-DIMENSIONAL GRAPHS IN
MATLAB
The learning objectives are:
MATLAB provides functions for visualizing 3-D scalar and the 3-D vector data. In MATLAB, one can specify
plot characteristics, such as viewing angle, perspective, lighting effect, light source, location and transparency.
3-dimenstional plotting function includes surface, contour, mesh, image plots simple and easily understandable.
This makes graphics one of the most powerful features of MATLAB.
MATLAB MANUALS 66
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
x=0:2*pi:5000;
y=sin(x);
z=x+5;
plot3(x,y,z)
xlabel ('X-Axis');
ylabel ('Y-Axis');
zlabel ('Z-Axis');
title ('Plot 3D Graph');
grid on;
Output
7.3.2 Task#02
Given is 𝒚 = 𝐬𝐢𝐧 𝒙 𝒂𝒏𝒅 𝒛 = 𝒙 + 𝟓 , 𝒇𝒐𝒓 𝟎 < 𝒙 < 𝟓𝟎𝟎𝟎
Obtain a 3D plot using a Comet Command?
Program
x=0:2*pi:5000;
y=sin(x);
z=x+5;
comet3(x,y,z) %OR comet3(x,y,z) we see graph is drawn
xlabel ('X-Axis');
ylabel ('Y-Axis');
zlabel ('Z-Axis');
title ('Use of Comet Command');
grid on
axis tight
MATLAB MANUALS 67
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Output
7.3.3 Task#03
𝐬𝐢𝐧 𝒓
Create a surface plot of the function: 𝒛 = 𝒓
where 𝒓 = √𝒙𝟐 + 𝒚𝟐 𝒇𝒐𝒓 − 𝟖 < 𝒙 < 𝟖 𝒂𝒏𝒅 − 𝟖 < 𝒚 < 𝟖?
Program
x=-8:0.5:8;
y=-8:0.5:8;
[X,Y]=meshgrid(x,y); % x and y changed into X,Y(now we use these X and
Y)
r=sqrt(X.^2+Y.^2);
Z=sin(r)./r;
surf(X,Y,Z)
Output
MATLAB MANUALS 68
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
7.3.4 Task#04
𝐬𝐢𝐧 𝒓
Create a mesh plot of the function: 𝒛 = 𝒓
where 𝒓 = √𝒙𝟐 + 𝒚𝟐 𝒇𝒐𝒓 − 𝟖 < 𝒙 < 𝟖 𝒂𝒏𝒅 − 𝟖 < 𝒚 < 𝟖?
Program
x=-8:0.5:8;
y=-8:0.5:8;
[X,Y]=meshgrid(x,y); %x and y changed into X,Y(now we use these X and Y)
r=sqrt(X.^2+Y.^2);
Z=sin(r)./r;
mesh(X,Y,Z)
Output
7.3.5 Task#05
𝐬𝐢𝐧 𝒓
Plot the function using “meshc”, “meshz” and “waterfall” commands using the function 𝒛 = 𝒓
where 𝒓 = √𝒙𝟐 + 𝒚𝟐 𝒇𝒐𝒓 − 𝟖 < 𝒙 < 𝟖 𝒂𝒏𝒅 − 𝟖 < 𝒚 < 𝟖. Create subplots for each command.
Program
x=-8:0.5:8;
y=-8:0.5:8;
[X,Y]=meshgrid(x,y);
r=sqrt(X.^2+Y.^2);
Z=sin(r)./r;
subplot (3,1,1);
meshc(X,Y,Z)
title ('meshc Graph');
subplot (3,1,2);
meshz(X,Y,Z)
title ('meshz Graph');
subplot (3,1,3);
waterfall(X,Y,Z)
title ('waterfall Graph');
MATLAB MANUALS 69
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Output
MATLAB MANUALS 70
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
7.3.6 Task#06
Write a program to illustrate the use of stem3 function to plot the following function:
𝒚 = 𝒙 𝐜𝐨𝐬 𝒙 𝒂𝒏𝒅 𝒛 = 𝒄𝒐𝒔𝒙𝒆𝒙/𝟓 + 𝟏 𝒇𝒐𝒓 𝟎 ≤ 𝒙 ≤ 𝟔𝝅
Program
x=0:pi/50:6*pi;
y=x.*cos(x);
z=exp(x/5).*cos(x)+1;
stem3(x,y,z)
xlabel ('X-Axis');
ylabel ('Y-Axis');
zlabel ('Z-Axis');
title ('Use of stem3 Command');
grid on
axis tight
Output
40
30
20
Z-Axis
10
-10
-20
10
15
0 10
-10 5
Y-Axis 0
X-Axis
MATLAB MANUALS 71
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
8 LAB#8
CONSTRUCTION OF STATISTICAL GRAPHS IN
MATLAB
The learning objectives are:
To learn the basic features of plotting a 3D graph
To draw multiple plots using ‘plot’, ‘hold’ and ‘line’ functions
To learn about different style options to vary color, marker and line-style
To draw specialized plots such as bar, histogram, pie plots
8.1 Introduction
MATLAB provides very good tools for 2-dimensional and 3-dimensional plots, 3-D volume
visualization, functions, tools for interactively creating plots and the ability to export results to many
popular graphics formats. It is possible to customized plots by adding multiple axis, changing line colors
and markers, adding annotation and legends.
In MATLAB, one can specify plot characteristics, such as viewing angle, perspective, lighting effect,
light source, location and transparency. This makes graphics one of the most powerful features of
MATLAB.
8.2 List of Commands
Function name Description
MATLAB MANUALS 72
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
x= [0 1 2 3 4 5 6];
y = [10 15 25 20 30 27 19];
bar (x,y,'c') % c is for cyan color
xlabel ('x-axis');
ylabel ('y-axis');
title ('Graph to show bar function');
Output
8.3.2 Task#02
Plot a bar graph to show the comparison of average temperature in city A, B and C for the for the
months from September to February, data is given as:
MATLAB MANUALS 73
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
ylabel('Temperature in Celsius');
legend ('City A’, ‘City B’, ‘City C');
title ('Comparison of Average Temperature in City A, B and C');
Output
25
Temperature in Celsius
20
15
10
0
1 2 3 4 5 6
Months from September to February
8.3.3 Task#03
Plot the Histogram graph with 15 bins using the random data?
Program
x=randn (200,1);
hist(x,15)
title ('Histogram to show the 200 random values in 15 bins')
Output
8.3.4 Task#04
Illustrate with the use of ‘hist’ function with number of bins specified by a vector P?
Program
x = randn(300,1);
P = -2:0.1:2;
MATLAB MANUALS 74
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
hist (x,P)
title ('Histogram to show the values of 300 and no of bins specified by
Vector');
Output
8.3.5 Task#05
Illustrate the use of ROSE Function?
Program
MATLAB MANUALS 75
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
8.3.6 Task#06
Illustrate the use PIE Function to show the concentration of different industries in the region as
per following data:
INDUSTRIES INDUSTRIAL UNITS
Cement 4
Textile 8
Software 20
Chemical 2
Telecom 7
Banking 10
Show the sliced and labeled pie chart?
Program
x=[4 8 20 2 7 10];
k=[1,0,0,1,1,0];
label=({'Cement','Textile','Software','Chemicel','Telecom','Banking'});
pie(x,k,label) %For 2D PIE Chart
Output
8.3.7 Task#07
Draw 3D bar graph for the data given as:
x= [0 1 2 3 4 5 6] and y = [10 15 25 20 30 27 19]?
Program
x= [0 1 2 3 4 5 6];
y = [10 15 25 20 30 27 19];
bar3 (x,y,'g')
xlabel ('x-axis');
ylabel ('y-axis');
title ('Graph to show bar 3D function');
MATLAB MANUALS 76
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Output
8.3.8 Task#08
Illustrate the use of pie3 function to show different professions people groups as per the following
data?
x = [12 15 13 11 6 10];
k = [0 0 1 0 0 1];
label = ({'Manager',
'Engineer','Professor','Doctor','Architect','Designer'});
pie3 (x, k, label)
title ('Persons in a Group using pie3 Function');
Output
MATLAB MANUALS 77
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
9 LAB#9
INTRODUCTION TO CONTROL STRUCTURES AND
THEIR IMPLEMENTATION
The learning objectives are:
MATLAB MANUALS 78
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
9.4 LOOPS
They are classified depending upon the no in which the iterations in a program are controlled, for and
while loops. In for loop the no of repetitions are already known but in while loop instructions are
executed until condition satisfied.
while (condition)
statement # 1;
statement # 2;
........................
statement # n;
end
The group of statements may include same statement which may alter the result of the condition, when
condition is false the loop is terminated.
MATLAB MANUALS 79
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
next statement;
where expression is a logic expression and give the result either true or false, if expression give true
result then the statements are executed till end otherwise not.
If expression
statement # 1;
statement # 2;
........................
statement # n;
else
statement # 1;
statement # 2;
........................
statement # n;
end
if the expression is true then if statements are executed and else statements are skipped or if not true
then else statements are executed and if statements are executed.
MATLAB MANUALS 80
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
MATLAB MANUALS 81
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
10 LAB#10
DEMONSTRATION AND MANIPULATION OF SOLUTION
OF TRANSCENDENTAL EQUATIONS BY ROOT
BRACKETING METHODS
The learning objectives are:
How does Root Bracketing Methods work?
Background of Bracketing Methods.
Algorithm.
Convergence sheet.
10.1 BI-SECTION METHOD
ALGORITHM
Newton’s method is a popular technique for the solution of nonlinear equations, but alternative methods
exist which may be preferable in certain situations. The Bisection method is yet another technique for
finding a solution to the nonlinear equation f(x) = 0, which can be used provided that the function f is
continuous. The motivation for this technique is drawn from Bolzano’s theorem for continuous
functions.
Theorem (Bolzano)
If the function f(x) is continuous in [a, b] and f(a).f(b) < 0 (i.e. the function f has values with different
signs at a and b), then a value c belongs to (a, b) exists such that f(c) = 0.
The bisection algorithm attempts to locate the value c where the plot of f crosses over zero, by checking
whether it belongs to either of the two sub-intervals [a, xm], [xm, b], where xm is the midpoint xm = (a
+ b)/2
The steps to apply the bisection method to find the root of the equation f ( x) 0 are
MATLAB MANUALS 82
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
1. Choose x and xu as two guesses for the root such that f ( x ) f ( xu ) 0 , or in other words,
f (x) changes sign between x and xu .
2. Estimate the root, xm , of the equation f ( x) 0 as the mid-point between x and xu as
x xu
xm =
2
xmnew - xmold
a = 100
xmnew
where
5. Compare the absolute relative approximate error a with the pre-specified relative error
tolerance s . If a s , then go to Step 3, else stop the algorithm. Note one should also check
whether the number of iterations is more than the maximum number of iterations allowed. If
so, one needs to terminate the algorithm and notify the user about it.
10.2 MATLAB CODE
10.2.1 Task
𝒅𝒄
𝒗 = 𝒘 − 𝑸𝒄 − 𝒌𝒗√𝒄
𝒅𝒕
Given the parameter values as follows:
𝒗 = 𝟏 × 𝟏𝟎𝟔 𝒎𝟑
𝑸 = 𝟏 × 𝟏𝟎𝟓 𝒎𝟑 /𝒚𝒆𝒂𝒓
𝒘 = 𝟏 × 𝟏𝟎𝟔 𝒈𝒎/𝒚𝒆𝒂𝒓
𝒌 = 𝟎. 𝟐𝟓 𝒎𝟎.𝟓 /𝒈𝟎.𝟓 /𝒚𝒆𝒂𝒓
The equation takes the form:
MATLAB MANUALS 83
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Solve for the steady-state concentration, find the root using Bisection method in MATLAB.
Program
clc
close all
clear all
for i=1:20
xr=(xa+xb)/2; % Bisection formula
f_xr=25*sqrt(xr)+10*xr-100;
RE=abs((xr-xb)/xr)*100;
else
xa=xr;
xb=xb;
MATLAB MANUALS 84
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Output
f=
@(x)25*sqrt(x)+10*x-100
ans =
-100
ans =
5.9017
ans =
79.0569
i xa xb xr f(xr) RE
1 0.00000 5.00000 2.50000 -35.47153 100.0000
2 2.50000 5.00000 3.75000 -14.08771 33.33333
3 3.75000 5.00000 4.37500 -3.95875 14.28571
4 4.37500 5.00000 4.68750 1.00159 6.66667
5 4.37500 4.68750 4.53125 -1.47067 3.44828
6 4.53125 4.68750 4.60938 -0.23261 1.69492
7 4.60938 4.68750 4.64844 0.38496 0.84034
8 4.60938 4.64844 4.62891 0.07630 0.42194
9 4.60938 4.62891 4.61914 -0.07813 0.21142
10 4.61914 4.62891 4.62402 -0.00091 0.10560
11 4.62402 4.62891 4.62646 0.03769 0.05277
12 4.62402 4.62646 4.62524 0.01839 0.02639
13 4.62402 4.62524 4.62463 0.00874 0.01320
14 4.62402 4.62463 4.62433 0.00392 0.00660
15 4.62402 4.62433 4.62418 0.00150 0.00330
16 4.62402 4.62418 4.62410 0.00030 0.00165
17 4.62402 4.62410 4.62406 -0.00031 0.00082
18 4.62406 4.62410 4.62408 -0.00000 0.00041
19 4.62408 4.62410 4.62409 0.00015 0.00021
20 4.62408 4.62409 4.62409 0.00007 0.00010
MATLAB MANUALS 85
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Graph
The steps to apply the false-position method to find the root of the equation f x 0 are as follows.
Choose x L and xU as two guesses for the root such that f xL f xU 0 , or in other words, f x
changes sign between x L and xU .
xU f x L x L f xU
xr
f x L f xU
xU f x L x L f xU
xr
f x L f xU
MATLAB MANUALS 86
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
x rnew x rold
a 100
x rnew
where
Compare the absolute relative approximate error a with the pre-specified relative error tolerance s .
If a s , then go to step 3, else stop the algorithm. Note one should also check
whether the number of iterations is more than the maximum number of iterations allowed. If so, one
needs to terminate the algorithm and notify the user about it.
Note that the false-position and bisection algorithms are quite similar. The only difference is the
formula used to calculate the new estimate of the root x r as shown in steps #2 and #4!
𝒅𝒄
𝒗 = 𝒘 − 𝑸𝒄 − 𝒌𝒗√𝒄
𝒅𝒕
Given the parameter values as follows:
𝒗 = 𝟏 × 𝟏𝟎𝟔 𝒎𝟑
𝑸 = 𝟏 × 𝟏𝟎𝟓 𝒎𝟑 /𝒚𝒆𝒂𝒓
𝒘 = 𝟏 × 𝟏𝟎𝟔 𝒈𝒎/𝒚𝒆𝒂𝒓
𝒌 = 𝟎. 𝟐𝟓 𝒎𝟎.𝟓 /𝒈𝟎.𝟓 /𝒚𝒆𝒂𝒓
The equation takes the form:
Solve for the steady-state concentration, find the root using Regula-Falsi method in MATLAB.
Program
clc
close all
clear all
MATLAB MANUALS 87
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
for i=1:15
xr= ((xa*f(xb)-xb*f(xa))./(f(xb)-f(xa))); % Regula-Falsi formula
f_xr=25*sqrt(xr)+10*xr-100;
RE=abs((xr-xb)/xr)*100;
else
xa=xr;
xb=xb;
f=
@(x)25*sqrt(x)+10*x-100
ans =
-100
ans =
5.9017
ans =
79.0569
MATLAB MANUALS 88
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
i xa xb xr f(xr) RE
1 0.00000 10.0000 5.58482 14.92869 79.05694
2 0.00000 5.58482 4.85937 3.70372 14.92869
3 0.00000 4.85937 4.68582 0.97516 3.70372
4 0.00000 4.68582 4.64057 0.26068 0.97516
5 0.00000 4.64057 4.62851 0.06997 0.26068
6 0.00000 4.62851 4.62527 0.01880 0.06997
7 0.00000 4.62527 4.62440 0.00505 0.01880
8 0.00000 4.62440 4.62417 0.00136 0.00505
9 0.00000 4.62417 4.62410 0.00037 0.00136
10 0.00000 4.62410 4.62409 0.00010 0.00037
11 0.00000 4.62409 4.62408 0.00003 0.00010
12 0.00000 4.62408 4.62408 0.00001 0.00003
13 0.00000 4.62408 4.62408 0.00000 0.00001
14 0.00000 4.62408 4.62408 0.00000 0.00000
15 0.00000 4.62408 4.62408 0.00000 0.00000
The root of given equation = 4.624081
Graph
MATLAB MANUALS 89
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
11 LAB#11
DEMONSTRATION AND MANIPULATION OF SOLUTION
OF TRANSCENDENTAL EQUATIONS BY OPEN
METHODS
The learning objectives are:
The steps of the Newton-Raphson method to find the root of an equation f x 0 are
4. Compare the absolute relative approximate error with the pre-specified relative error
tolerance, s . If a > s , then go to Step 2, else stop the algorithm. Also, check if the
number of iterations has exceeded the maximum number of iterations allowed. If so, one
needs to terminate the algorithm and notify the user.
𝒅𝒄
𝒗 = 𝒘 − 𝑸𝒄 − 𝒌𝒗√𝒄
𝒅𝒕
Given the parameter values as follows:
𝒗 = 𝟏 × 𝟏𝟎𝟔 𝒎𝟑
MATLAB MANUALS 90
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
𝑸 = 𝟏 × 𝟏𝟎𝟓 𝒎𝟑 /𝒚𝒆𝒂𝒓
𝒘 = 𝟏 × 𝟏𝟎𝟔 𝒈𝒎/𝒚𝒆𝒂𝒓
𝒌 = 𝟎. 𝟐𝟓 𝒎𝟎.𝟓 /𝒈𝟎.𝟓 /𝒚𝒆𝒂𝒓
The equation takes the form:
Solve for the steady-state concentration, find the root using Newton-Raphson method in
MATLAB.
Program
%%
clc
clear all
close all
f=@(x) 25*sqrt(x)+10*x-100 % Let steady-state concentration = x
Df=@(x) 12.5*x^(-1/2)+10;
f(0)
f(5)
f(10)
fplot(f,[0,10])
xlabel ('Steady-state concentration, c');
ylabel ('f(c)');
title ('NEWTON RAPHSON METHOD');
grid on
gtext('xr');
for i=1:5
xr=xa - (f(xa)/Df(xa));
f_xr=25*sqrt(xr)+10*xr-100;
Df_xr=12.5*xr^(-1/2)+10;
RE=abs((xr-xa)/xr)*100;
xa=xr;
fprintf ('%6d %15.5f %15.5f %15.5f %18.5f \n' ,
i,xa,xr,f_xr,RE);
f=
@(x) 25*sqrt(x)+10*x-100
ans =
-100
MATLAB MANUALS 91
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
ans =
5.9017
ans =
79.0569
i xa xr f(xr) RE
1 4.33399 4.33399 -4.61447 130.73415
Graph
The Newton Raphson method of solving a non-linear equation of 𝑓(𝑥) = 0 is given by the iterative
formula:
𝑓’(𝑥) = ((𝑓(𝑥𝑖) – 𝑓(𝑥𝑖 − 1))/(𝑥𝑖 – 𝑥𝑖 − 1)).
MATLAB MANUALS 92
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
One of that’s method drawback is that we find derivative of that function, with availability of symbolic
manipulator like math, MAT-Lab and they are more convenient, laborious, intractable if function derive
as part of numerical scheme. In overcome that drawback th function derivative is reduce to:
Put in above formula:
𝑋𝑖 + 1 = 𝑥𝑖 – (𝑓(𝑥𝑖) ∗ ( 𝑥𝑖 – 𝑥𝑖 − 1)/( 𝑓(𝑥𝑖) – 𝑓(𝑥𝑖 − 1)).
The above eq. Is called the Secant Method, requires 2 initial guesses and no need to bracket the root of
the eq. It is an open method or may converge and faster than the Bi-Sectional Method but slower than
Newton Raphson Method.
The Newton-Raphson method of solving a nonlinear equation f ( x) 0 is given by the iterative
formula
f ( xi )
xi 1 = xi (1)One of
f ( xi )
the drawbacks of the Newton-Raphson method is that you have to evaluate the derivative of the
function. With availability of symbolic manipulators such as Maple, MathCAD, MATHEMATICA
and MATLAB, this process has become more convenient. However, it still can be a laborious
process, and even intractable if the function is derived as part of a numerical scheme. To overcome
these drawbacks, the derivative of the function, f (x) is approximated as
f ( xi ) f ( xi 1 )
f ( xi ) (2)
xi xi 1
f ( xi )( xi xi 1 )
xi 1 xi (3)
f ( xi ) f ( xi 1 )
The above equation is called the secant method. This method now requires two initial guesses, but
unlike the bisection method, the two initial guesses do not need to bracket the root of the equation. The
secant method is an open method and may or may not converge. However, when secant method
converges, it will typically converge faster than the bisection method. However, since the derivative is
approximated as given by Equation (2), it typically converges slower than the Newton-Raphson method.
MATLAB MANUALS 93
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
𝒅𝒄
𝒗 = 𝒘 − 𝑸𝒄 − 𝒌𝒗√𝒄
𝒅𝒕
Given the parameter values as follows:
𝒗 = 𝟏 × 𝟏𝟎𝟔 𝒎𝟑
𝑸 = 𝟏 × 𝟏𝟎𝟓 𝒎𝟑 /𝒚𝒆𝒂𝒓
𝒘 = 𝟏 × 𝟏𝟎𝟔 𝒈𝒎/𝒚𝒆𝒂𝒓
𝒌 = 𝟎. 𝟐𝟓 𝒎𝟎.𝟓 /𝒈𝟎.𝟓 /𝒚𝒆𝒂𝒓
The equation takes the form:
Solve for the steady-state concentration, find the root using Secant method in MATLAB.
Program
%%
clc
close all
clear all
xa=0;
xb=10;
f_xa=@(x) 25*sqrt(xa)+10*xa-100;
f_xb=@(x) 25*sqrt(xb)+10*xb-100;
for i=1:8
xr=(xa*f(xb)-xb*f(xa))/(f(xb)-f(xa));
f_xr=25*sqrt(xr)+10*xr-100;
RE=abs((xr-xa)/xr)*100;
MATLAB MANUALS 94
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
xb=xr;
f_xb=f_xr;
end
fprintf ('\n The root of given equation = %f \n' , xr);
Output
f=
@(x)25*sqrt(x)+10*x-100
ans =
-100
ans =
5.9017
ans =
79.0569
i xa xb xr f(xr) RE
MATLAB MANUALS 95
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Graph
In numerical Analysis, this method is used to find the fixed point iteration, more specifically given
function defines on the real values and a point xb in the domain of f, the fixed point iteration is:
𝑥n+1 = 𝑔(𝑥n) 𝑛 = 0,1,2,3. . . . .
which gives rise to sequence x0, x1, x2 , ....., which is hoped to convert to a point x, if f is continuous,
then one can prove that the obtained ‘x’ is a fixed point of f, i.e.
𝑓(𝑥) = 𝑥
More generally the function f can be defined on any matrix space with values in that same space.
𝒅𝒄
𝒗 = 𝒘 − 𝑸𝒄 − 𝒌𝒗√𝒄
𝒅𝒕
Given the parameter values as follows:
𝒗 = 𝟏 × 𝟏𝟎𝟔 𝒎𝟑
𝑸 = 𝟏 × 𝟏𝟎𝟓 𝒎𝟑 /𝒚𝒆𝒂𝒓
𝒘 = 𝟏 × 𝟏𝟎𝟔 𝒈𝒎/𝒚𝒆𝒂𝒓
𝒌 = 𝟎. 𝟐𝟓 𝒎𝟎.𝟓 /𝒈𝟎.𝟓 /𝒚𝒆𝒂𝒓
The equation takes the form:
MATLAB MANUALS 96
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Solve for the steady-state concentration, find the root using Fixed-point iteration method in
MATLAB.
Program
%%
clc
close all
clear all
for i=1:45
xr=g(xa);
g_xr=10-2.5*sqrt(xr);
RE=abs((xr-xa)/xr)*100;
fprintf('\n%3d %15.7f %15.7f %15.7f %15.7f
%18.8f\n',i,xa,xr,g_xr,RE);
xa=xr;
end
fprintf('\n The root of given equation = %f \n',xr);
Output
f=
@(x) 25*sqrt(x)+10*x-100
ans =
-100
ans =
5.9017
MATLAB MANUALS 97
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
ans =
79.0569
i xa xr g_xr RE
1 0.0000000 10.0000000 2.0943058 100.0000000
MATLAB MANUALS 98
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
MATLAB MANUALS 99
SESSSION: 2016-2020 Chemical Engineering Department
2222222020
Graph
12 LAB#12:
DEMONSTRATION AND MANIPULATION OF SOLUTION OF
SYSTEM OF LINEAR EQUATIONS
The learning objectives are:
How does Lagrange and Newton Divided Difference Interpolation Formula work?
Background.
Algorithms.
Convergence Sheet
12.1 JACOBI’S METHOD:
ALGORITHM
If the Diagonal elements are non-zero each eq. Is re written for the corresponding unknown, that is,
the 1st eq. Is rewritten with ‘x1’ on the LHS and 2nd with ‘x2’ on LHS and so on.
i.e.
x1 = (c1 - a12x2 - a13x3 - ...................... - a1nxn ) / a11.
x2 = (c2 - a21x1 - a23x3 - ...................... - a2nxn ) / a22.
x3 = (c3 – a31x1 – a32x2 - ...................... - a3nxn ) / a33.
...............................................................................
...............................................................................
xn = (cn – an1x1 – an2x2 - ...................... - an,n-1xn-1 ) / an-1.
for i=1:10
x(i+1) = (b1 - a12*y(i) - a13*z(i))/a11;
y(i+1) = (b2 - a21*x(i) - a23*z(i))/a22;
z(i+1) = (b3 - a31*x(i) - a32*y(i))/a33;
REx = (abs((x(i+1)-x(i))/x(i+1)))*100;
REy = (abs((y(i+1)-y(i))/y(i+1)))*100;
REz = (abs((z(i+1)-z(i))/z(i+1)))*100;
hold on
mesh (x,y,z3)
hold off
xlabel('x-axis');
ylabel('y-axis');
zlabel('z-axis');
title ('Plotting system of linear equations');
grid on
% Shortcut method: x=inv(A)*B;
Output
x = 3.000000
y = -2.500000
z = 7.000000
Graph
________________________________________________________________________________________
If the Diagonal elements are non-zero each eq. Is re written for the corresponding unknown, that is,
the 1st eq. Is rewritten with ‘x1’ on the LHS and 2nd with ‘x2’ on LHS and so on.
i.e.
x1 = (c1 - a12x2 - a13x3 - ...................... - a1nxn ) / a11.
x2 = (c2 - a21x1 - a23x3 - ...................... - a2nxn ) / a22.
x3 = (c3 – a31x1 – a32x2 - ...................... - a3nxn ) / a33.
...............................................................................
...............................................................................
xn = (cn – an1x1 – an2x2 - ...................... - an,n-1xn-1 ) / an-1.
clc
clear all
close all
x(1)=0;
y(1)=0;
z(1)=0;
fprintf('i x(i+1) y(i+1) z(i+1) REx REy REz \n');
for i=1:6
x(i+1) = (b1 - a12*y(i) - a13*z(i))/a11;
y(i+1) = (b2 - a21*x(i+1) - a23*z(i))/a22;
z(i+1) = (b3 - a31*x(i+1) - a32*y(i+1))/a33;
REx = (abs((x(i+1)-x(i))/x(i+1)))*100;
REy = (abs((y(i+1)-y(i))/y(i+1)))*100;
REz = (abs((z(i+1)-z(i))/z(i+1)))*100;
X = [0:20];
Y = [0:20];
[x,y] = meshgrid (X,Y);
mesh(x,y,z1)
hold on
mesh (x,y,z2)
hold on
mesh (x,y,z3)
hold off
xlabel('x-axis');
ylabel('y-axis');
zlabel('z-axis');
title ('Plotting system of equations');
grid on
Output
x = 3.000000
y = -2.500000
z = 7.000000
Graph
13 LAB#13
DEMONSTRATION AND MANIPULATION OF
INTERPOLATION BY LAGRANGE’S METHOD AND
NEWTON’S DIVIDED DIFFERENCE
The learning objectives are:
How does Lagrange and Newton Divided Difference Interpolation Formula work?
Background.
Algorithms.
Convergence Sheet
13.1 LAGRANGE INTERPOLATION METHOD
ALGORITHM
Polynomial interpolation involves finding a polynomial of order ‘n’ that passes through the ‘n+1’ data
points. One of the methods used to find this polynomial is called ‘Lagrange-Interpolation Formula’,
other methods includes Newton’s divided difference polynomials method and the direct methods.
The Lagrange-Interpolation polynomial is given by:
𝑃𝑛(𝑥) = ∑ 𝐿𝑖(𝑥). 𝑓(𝑥𝑖).
Where n in Pn(x) stands for the nth order polynomial that approximates the function y=f(x) given that
n+1 data points as (x0,y0),( x1,y1), ( x2,y2),.................... ( xn-1,yn-1), ( xn,yn).
and
Li(x) is a weighting function that includes a product of n-1 terms and with terms of i=1 omitted.
𝑻: 0 8 16 24 32 40
𝑶(𝑻): 14.621 11.843 9.870 8.418 7.305 6.413
Program
clc
clear all
close all
% Declaring Table
x=[0,8,16,24,32,40];
y=[14.621,11.843,9.870,8.418,7.305,6.413];
n=length(x);
for i=1:n
L=1; % Initializing Lagranges L
for j=1:n
if (j~=i)
L=L*(xa-x(j))/(x(i)-x(j));
end
end
ya=ya+L*y(i);
end
Output
fx =
Graph
Lagrange Interpolation
16
14
y-values
12
Interpolating point
10
6
0 10 20 30 40
x-values
For Newton’s divided difference method let us revisit the quadratic polynomial interpolation formula
f 2 ( x) b0 b1 ( x x0 ) b2 ( x x0 )( x x1 )
where
b0 f ( x0 )
f ( x1 ) f ( x0 )
b1
x1 x0
f ( x 2 ) f ( x1 ) f ( x1 ) f ( x0 )
x 2 x1 x1 x0
b2
x 2 x0
Note that b0 , b1 , and b2 are finite divided differences. b0 , b1 , and b2 are the first, second, and third
finite divided differences, respectively. We denote the first divided difference by
f [ x0 ] f ( x0 )
f ( x1 ) f ( x0 )
f [ x1 , x0 ]
x1 x0
f [ x2 , x1 ] f [ x1 , x0 ]
f [ x2 , x1 , x0 ]
x 2 x0
f ( x2 ) f ( x1 ) f ( x1 ) f ( x0 )
x2 x1 x1 x0
x 2 x0
Rewriting,
f 2 ( x) f [ x0 ] f [ x1 , x0 ]( x x0 ) f [ x2 , x1 , x0 ]( x x0 )( x x1 )
This leads us to writing the general form of the Newton’s divided difference polynomial for n 1 data
points, x0 , y0 , x1 , y1 ,......,xn1 , yn1 , xn , yn , as
where
b0 f [ x0 ]
b1 f [ x1 , x0 ]
b2 f [ x2 , x1 , x0 ] ……
bn f [ xn , xn1 ,....,x0 ]
bm f [ xm ,........,x0 ]
f [ xm ,........,x1 ] f [ xm 1 ,........,x0 ]
xm x0
From the above definition, it can be seen that the divided differences are calculated recursively.
𝑻: 0 8 16 24 32 40
𝑶(𝑻): 14.621 11.843 9.870 8.418 7.305 6.413
%%
% Newton Divided Difference
clc
clear all
close all
x=[0,8,16,24,32,40];
transposeofx=x';
y=[14.621,11.843,9.870,8.418,7.305,6.413];
xa=27; % point where y is evaluated
yo=14.621;
n=length(x);
D=zeros(n,n); % Matrix of zeros of nxn where n= number of elements in x
D(:,1)=y; % All rows and 1st column of D is replaced by y
for j=2:n
for i=j:n
fprintf(' Newtons Divided difference table:\n');
D(i,j)=(D(i,j-1)-D(i-1,j-1))/(x(i)-x(i-j+1))
end
end
for i=n:-1:2
for j=n:-1:2
p=1;
if i==j
p=p*(xa-(x(i)))*D(i,j);
end
end
end
ya=yo+p;
fprintf(' ya=%f\n',ya);
exact=7.96820;
fprintf(' exact value=7.96820\n');
RE=abs((exact-ya)/exact)*100;
fprintf(' Percentage Relative Error=%f \n',RE);
Output
14 LAB#14
DEMONSTRATION AND MANIPULATION OF
NUMERICAL INTEGRATION BY TRAPEZOIDAL RULE
AND SIMPSON’S 1/3 RULE
The learning objectives are:
Just like in multiple-segment trapezoidal rule, one can subdivide the interval a, b into n segments and
apply Simpson’s 1/3 rule repeatedly over every two segments. Note that n needs to be even. Divide
interval a, b into n equal segments, so that the segment width is given by
ba
h .
n
Now
b xn
f ( x)dx f ( x)dx
a x0
where
x0 a xn b
b x2 x4 xn 2 xn
𝑏 𝑛−1
(𝑏 − 𝑎)
∫ 𝑓(𝑥)𝑑𝑥 = (𝑓(𝑥0 ) + 𝑓(𝑥𝑛 ) + 2 ∑ 𝑓(𝑥𝑖 ))
𝑎 2𝑛
𝑖=1
Program
%%
% Trapezoidal rule
clc
clear all
close all
f=@(x) (0.2+25*x-200*x^2+675*x^3-900*x^4+400*x^5);
fplot(f,[0,1])
xlabel('x');
ylabel('f(x)');
title('Finding area using Trapezoidal rule');
gtext('Area under curve');
grid on
a=0;
b=0.8;
n=10;
h=(b-a)/n;
for i=a+h:h:b-h
x=x+h; % Increment in x-values
y=y+feval(f,i); % add up the area of each trapezoid from y1 to yn-
1
I1=h*y;
end
fprintf('\n I1=%f',I1);
fprintf('\n I2=%f',I2);
fprintf('\n Trapezoidal Area=%f',I);
Output
I1=1.597763
I2=0.017280
Trapezoidal Area=1.615043
Graph
2
f(x)
-1
-2
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
x
Just like in multiple-segment trapezoidal rule, one can subdivide the interval a, b into n segments and
apply Simpson’s 1/3 rule repeatedly over every two segments. Note that n needs to be even. Divide
interval a, b into n equal segments, so that the segment width is given by
ba
h .
n
b xn
f ( x)dx f ( x)dx
a x0
Now
Where x0 a xn b
b x2 x4 xn 2 xn
f ( x0 ) 4 f ( x1 ) f ( x2 ) f ( x 2 ) 4 f ( x3 ) f ( x 4 )
b
f ( x)dx ( x
a
2 x0 )
6
( x4 x2 )
6 ...
f ( x n 4 ) 4 f ( x n 3 ) f ( x n 2 ) f ( x n 2 ) 4 f ( x n 1 ) f ( x n )
( xn2 xn4 ) ( xn xn2 )
6 6
Since
xi xi 2 2h i 2, 4, ..., n
f ( x0 ) 4 f ( x1 ) f ( x2 ) f ( x 2 ) 4 f ( x3 ) f ( x 4 )
b
f ( x)dx 2h
a
6 2 h 6 ...
f ( x n 4 ) 4 f ( x n 3 ) f ( x n 2 ) f ( x n 2 ) 4 f ( x n 1 ) f ( x n )
2h 2h
6 6
h
f ( x0 ) 4 f ( x1 ) f ( x3 ) ... f ( xn1 ) 2 f ( x2 ) f ( x4 ) ... f ( xn2 ) f ( xn )
3
n 1 n2
h
f ( x 0 ) 4 f ( xi ) 2 f ( xi ) f ( x n )
3 i 1 i 2
i odd i even
ba n 1 n 2
b
f ( x )dx f ( x 0 ) 4 f ( xi ) 2 f ( x i ) f ( x n )
3n i 1 i 2
a
i odd i even
Program
grid on
a=0;
b=0.8;
n=10;
h=(b-a)/n;
y1=0; % Initializing the point for loop 1
y2=0; % Initializing the point for loop 2
x=a; % Initializing 'x' point
for i=a+h:2*h:b-h % for-loop for odd points x1, x3, x5, ..., xn-2
x=x+h; % Increment in x-values
y1=y1+feval(f,i); % add up the area of odd points
end
I1=(4*h*y1)/3;
fprintf('\n I1=%f',I1);
for j=a+2*h:2*h:b-h % for-loop for even points x2,x4,x6,...,xn-1
y2=y2+feval(f,j); % add up the area of even points
end
I2=(2*h*y2)/3;
fprintf('\n I2=%f',I2);
I3=(h*(feval(f,a)+feval(f,b))/3); % Area of yo and yn
fprintf('\n I3=%f',I3);
I=I1+I2+I3; % Total Area
fprintf('\n Area using Simpsons 1/3 Rule=%f \n',I);
Output
I1=1.126803
I2=0.501774
I3=0.011520
Area using Simpsons 1/3 Rule=1.640096
Graph
2
f(x)
-1
-2
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
x
15 LAB#15
DEMONSTRATION AND MANIPULATION OF SOLUTION
OF FIRST ORDER DIFFERENTIAL EQUATIONS BY
MODIFIED EULER’S METHOD AND R.K. METHOD OF
ORDER 4
The learning objectives are:
How does Modified Euler’s method and Runge-Kutta method of order-4 work?
Background.
Algorithms.
Convergence Sheet
15.1 MODIFIED EULERS METHOD
ALGORITHM
The objective in numerical methods is, as always, to achieve the most accurate and reliable result with
least effort. For integrating the Initial value problem, the effort is usually measured by the number of
times the function 𝑓(𝑡, 𝑦) must be evaluated in stepping from a to b. As we will see, a simple
improvement doubles the number of function evaluations per step, but yields a second order method-a
winning strategy.
The Modified Euler’s method starts with an Euler step, giving a provisional value for 𝑦𝑖+1 at the next
time 𝑡𝑖+1 .
′
𝑦𝑖+1 = 𝑦𝑖 + ℎ𝑓(𝑡𝑖 , 𝑦𝑖 ) eq(1)
The step actually taken looks like an Euler step, but with ‘f’ replaced by the average of ‘f’ at the starting
point of the step and ‘f’ at the provisional point.
ℎ ′
𝑦𝑖+1 = 𝑦𝑖 + 2 [𝑓(𝑡𝑖 , 𝑦𝑖 )+𝑓(𝑡𝑖+1 , 𝑦𝑖+1 )]
eq(2)
ℎ
𝑦𝑖+1 = 𝑦𝑖 + [𝑓(𝑡𝑖 , 𝑦𝑖 ) + 𝑓(𝑡𝑖+1 , 𝑦𝑖 + ℎ𝑓(𝑡𝑖 , 𝑦𝑖 ))]
2
which is the Iterative formula for the Modified Euler’s method.
𝒅𝒚
= 𝟒𝒆𝟎.𝟖𝒙 − 𝟎. 𝟓𝒚
𝒅𝒙
Program
%%
% Modified Eulers method
clc
clear all
close all
f=@(x,y) 4*exp(0.8*x)-0.5*y;
h=0.5; % Step-size
x=0:h:1.5; % range of x variable
n=length(x); % Number of elements in x vector
x(1)=0; % xo
y(1)=2; % yo
for i=1:n-1
y(i+1)=y(i)+h*feval(f,x(i)+h/2,y(i)+0.5*h*feval(f,x(i),y(i)));
fprintf('%3d %10.5f %17.10f\n',i,x(i),y(i+1));
end
Solution of first order Differential Equation using Modified Euler method is: 9.727924
To understand the Runge-Kutta 2nd order method, we need to derive Euler’s method from the Taylor
series.
2 3
yi 1 y i
dy
xi 1 xi 1 d y
2
xi 1 xi 2 1 d y
3
xi 1 xi 3 ...
dx xi , yi 2! dx xi , yi
3! dx xi , yi
2! 3!
As you can see the first two terms of the Taylor series
yi 1 yi f xi , yi h
are Euler’s method and hence can be considered to be the Runge-Kutta 1st order method.
f xi , yi 2 f xi , yi 3
Et h h ...
2! 3!
So what would a 2nd order method formula look like. It would include one more term of the Taylor
series as follows.
yi 1 yi f xi , yi h f xi , yi h 2
1
2!
However, we already see the difficulty of having to find f x, y in the above method. What Runge
and Kutta did was write the 2nd order method as
yi 1 yi a1k1 a2 k 2 h
where
k1 f xi , yi
This form allows one to take advantage of the 2nd order method without having to calculate f x, y .
The formula described in this chapter was developed by Runge. This formula is same as Simpson’s 1/3
rule, if f x, y were only a function of x . There are other versions of the 4th order method just like
there are several versions of the second order methods. The formula developed by R.K. is:
y i 1 y i
h
k1 2k 2 2k 3 k 4
6
where
k1 f xi , yi
1 1
k 2 f xi h, y i k1
2 2
1 1
k 3 f xi h, y i k 2
2 2
k 4 f xi h, yi k3
This formula is the same as the Simpson’s 3/8 rule, if f x, y is only a function of x . In addition, the
fourth order Runge-Kutta method is similar to the Improved Euler’s method in that multiple estimates
of the slope are developed in order to come up with an improved average slope for the interval.
𝒅𝒚
= 𝟒𝒆𝟎.𝟖𝒙 − 𝟎. 𝟓𝒚
𝒅𝒙
With an initial condition 𝒚(𝟎) = 𝟐 using 𝒉 = 𝟎. 𝟓 with the range of 𝒙 = 𝟎 to 𝒙 = 𝟏
Program
%%
clc
clear all
close all
h=0.5; % step-size
x=0:h:1;
n=length(x);
x(1)=0; % value of x in initial condition
y(1)=2; % value of y in initial condition
f=@(x,y) (4*exp(0.8*x))-0.5*y;
fprintf('Runge-Kutta method of order-4\n');
fprintf(' i k1 k2 k3 k4 y(i+1)\n');
for i=1:n
k1=f(x(i),y(i));
k2=f(x(i)+0.5*h,y(i)+0.5*k1);
k3=f(x(i)+0.5*h,y(i)+0.5*k2);
k4=f(x(i)+h,y(i)+k3);
y(i+1)=y(i)+(h*(k1+2*(k2+k3)+k4))/6;
fprintf('%3d %10.5f %10.5f %10.5f %10.5f
%10.5f\n',i,k1,k2,k3,k4,y(i+1));
end
Graph
Exact solution
5.5
4.5
y-axis
3.5
2.5
2
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
x-axis