Matlab Manuals

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

SESSSION: 2016-2020 Chemical Engineering Department

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

2.9 Special Constants & Variables ............................................................................................................. 15


2.10 Built-in Functions ................................................................................................................................ 15
2.11 Element by element operation ........................................................................................................... 16
2.12 ILLUSTRATIVE PROGRAMS .................................................................................................................. 17
2.12.1 Task#1.......................................................................................................................................... 17
2.12.2 Task#2.......................................................................................................................................... 17
2.12.3 Task#3.......................................................................................................................................... 18
2.12.4 Task4#.......................................................................................................................................... 18
2.12.5 Task#5.......................................................................................................................................... 18
2.12.6 Task#6.......................................................................................................................................... 19
2.12.7 Task#7.......................................................................................................................................... 20
2.12.8 Task#8.......................................................................................................................................... 21
LAB#3................................................................................................................................................................... 22
IMPLEMENTATION OF VECTORS ......................................................................................................................... 22
3.1 Introduction ........................................................................................................................................ 22
3.2 Arrays .................................................................................................................................................. 22
3.3 Scalars and Vectors ............................................................................................................................. 22
3.4 Assigning data to elements of a Scalar/Vector ................................................................................... 22
3.4.1 Row vector .................................................................................................................................. 22
3.4.2 Column vector ............................................................................................................................. 22
3.4.3 Scalar ........................................................................................................................................... 23
3.5 Creation of evenly spaced Row-vectors .............................................................................................. 23
3.6 Commands for Evenly Spaced Row-Vectors ....................................................................................... 23
3.7 Built-In Functions for Handling Arrays ................................................................................................ 23
3.8 Built-In Functions for Analyzing Arrays ............................................................................................... 24
3.9 Matrix .................................................................................................................................................. 25
3.10 Matrix Subscripts/Indices .................................................................................................................... 26
3.11 Colon for a Matrix ............................................................................................................................... 26
3.12 Element By Element Operations ......................................................................................................... 26
3.13 Some Useful Commands Related To Matrices .................................................................................... 27
3.14 Generation of Special Matrices ........................................................................................................... 27
3.15 ILLUSTRATIVE PROGRAMS .................................................................................................................. 28
3.15.1 Task#1.......................................................................................................................................... 28

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

CONSTRUCTION OF STATISTICAL GRAPHS IN MATLAB ....................................................................................... 72


8.1 Introduction ........................................................................................................................................ 72
8.2 List of Commands ................................................................................................................................ 72
8.3 ILLUSTRATIVE PROGRAMS .................................................................................................................. 73
8.3.1 Task#01........................................................................................................................................ 73
8.3.2 Task#02........................................................................................................................................ 73
8.3.3 Task#03........................................................................................................................................ 74
8.3.4 Task#04........................................................................................................................................ 74
8.3.5 Task#05........................................................................................................................................ 75
8.3.6 Task#06........................................................................................................................................ 76
8.3.7 Task#07........................................................................................................................................ 76
8.3.8 Task#08........................................................................................................................................ 77
LAB#9................................................................................................................................................................... 78
INTRODUCTION TO CONTROL STRUCTURES AND THEIR IMPLEMENTATION ..................................................... 78
9.1 Introduction ........................................................................................................................................ 78
9.2 LOOPING STRUCTURES ........................................................................................................................ 78
9.3 BRANCHING STRUCTURES ................................................................................................................... 78
9.4 LOOPS .................................................................................................................................................. 79
9.5 FOR LOOP ............................................................................................................................................ 79
9.6 NESTED FOR LOOP............................................................................................................................... 79
9.7 WHILE LOOP ........................................................................................................................................ 79
9.8 BRANCHES CONTROL STRUCUTRE ...................................................................................................... 79
9.9 IF CONTROL STRUCTURE ..................................................................................................................... 80
9.10 IF STRUCUTRE ...................................................................................................................................... 80
9.11 IF-ELSE STRUCUTRE ............................................................................................................................. 80
9.12 IF-ELSE-IF STRUCTURE ......................................................................................................................... 81
9.13 NESTED IF STRUCTURE ........................................................................................................................ 81
LAB#10................................................................................................................................................................. 82
DEMONSTRATION AND MANIPULATION OF SOLUTION OF TRANSCENDENTAL EQUATIONS BY ROOT
BRACKETING METHODS ...................................................................................................................................... 82
10.1 BI-SECTION METHOD........................................................................................................................... 82
10.2 MATLAB CODE ..................................................................................................................................... 83
10.2.1 Task.............................................................................................................................................. 83

MATLAB MANUALS 5
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

10.3 REGULA-FALSI METHOD ...................................................................................................................... 86


10.4 MATLAB CODE ..................................................................................................................................... 87
10.4.1 Task.............................................................................................................................................. 87
LAB#11................................................................................................................................................................. 90
DEMONSTRATION AND MANIPULATION OF SOLUTION OF TRANSCENDENTAL EQUATIONS BY OPEN METHODS
............................................................................................................................................................................. 90
11.1 NEWTON-RAPHSON METHOD ............................................................................................................ 90
11.2 MATLAB CODE ..................................................................................................................................... 90
11.2.1 Task.............................................................................................................................................. 90
11.3 SECANT METHOD ................................................................................................................................ 92
11.4 MATLAB CODE ..................................................................................................................................... 94
11.4.1 Task.............................................................................................................................................. 94
11.5 FIXED POINT ITERATION METHOD ...................................................................................................... 96
11.6 MATLAB CODE ..................................................................................................................................... 96
11.6.1 Task.............................................................................................................................................. 96
LAB#12: ............................................................................................................................................................. 101
DEMONSTRATION AND MANIPULATION OF SOLUTION OF SYSTEM OF LINEAR EQUATIONS ......................... 101
12.1 JACOBI’S METHOD:............................................................................................................................ 101
12.2 MATLAB CODE ................................................................................................................................... 102
12.2.1 Task............................................................................................................................................ 102
12.3 GUASS-SEIDEL METHOD .................................................................................................................... 104
12.4 MATLAB CODE ................................................................................................................................... 104
12.4.1 Task............................................................................................................................................ 104
LAB#13............................................................................................................................................................... 107
DEMONSTRATION AND MANIPULATION OF INTERPOLATION BY LAGRANGE’S METHOD AND NEWTON’S
DIVIDED DIFFERENCE ........................................................................................................................................ 107
13.1 LAGRANGE INTERPOLATION METHOD.............................................................................................. 107
13.2 MATLAB CODE ................................................................................................................................... 107
13.2.1 Task............................................................................................................................................ 107
13.3 NEWTON DIVIDED DIFFERENCE INTERPOLATION METHOD: ............................................................ 109
13.4 MATLAB CODE ................................................................................................................................... 111
13.4.1 Task............................................................................................................................................ 111
LAB#14............................................................................................................................................................... 113

MATLAB MANUALS 6
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

DEMONSTRATION AND MANIPULATION OF NUMERICAL INTEGRATION BY TRAPEZOIDAL RULE AND


SIMPSON’S 1/3 RULE ......................................................................................................................................... 113
14.1 TRAPEZOIDAL RULE ........................................................................................................................... 113
14.2 MATLAB CODE ................................................................................................................................... 114
14.2.1 Task............................................................................................................................................ 114
14.3 SIMPSONS 1/3 RULE .......................................................................................................................... 115
14.4 MATLAB CODE ................................................................................................................................... 116
14.4.1 Task............................................................................................................................................ 116
LAB#15............................................................................................................................................................... 118
DEMONSTRATION AND MANIPULATION OF SOLUTION OF FIRST ORDER DIFFERENTIAL EQUATIONS BY
MODIFIED EULER’S METHOD AND R.K. METHOD OF ORDER 4 ........................................................................ 118
15.1 MODIFIED EULERS METHOD ............................................................................................................. 118
15.2 MATLAB CODE ................................................................................................................................... 119
15.2.1 Task............................................................................................................................................ 119
15.3 RUNGE-KUTTA METHOD OF ORDER-4 .............................................................................................. 120
15.4 MATLAB CODE ................................................................................................................................... 121
15.4.1 Task............................................................................................................................................ 121

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

1.3 Data Analysis and Visualization


 Preprocessing
 Fast and accurate analysis (Correlation, Fourier analysis and Filtering, Basic Statistics and
Curve fitting)
 Built-in functions for Matrix operations (Cholesky factorization, LU Factorization)
 Special Math functions (Airy function, Bessel function, Beta and Gamma function, Laplace
transforms, Fourier transforms, Interpolation, Polynomials and ODE solvers)
 Built-in Graphics for Engineering and Science (2D and 3D Plots, Volume Visualization)

MATLAB MANUALS 8
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

1.4 MATLAB Environment

The major components of MATLAB environment are as follows:


 Command window
 Command history
 Workspace
 Current folder
 Figure window
 Edit window
1.4.1 Command Window
Whenever MATLAB is involved the main window called command window is activated. The command
window displays the command prompt “>>” and a cursor where commands are entered and are executed
instantaneously on pressing the “enter” key of the keyboard. Commands can be run by typing them in
the command window.
1.4.2 Command History Window
It consists of a list of all the commands that are entered at the command window. It consists of
commands of previous session also. These commands remain in the list untile they are deleted. Any
command may be executed by selecting and double clicking it with mouse. A program file may be
created by selecting a set of commands and right clicking the mouse. On right clicking the mouse, pop-
up menu is displayed. A program file containing the selected commands can be created by choosing
“Create M.file” option from menu.

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.

1.4.5 Edit Window


An edit window is used to create a new program file or to modify existing files. In the window, programs
can be written, edited and save. The programs written using a MATALB editor are automatically
assigned an extension “.m” by the editor and are known as M. files. A new M. file can be created by
selecting an appropriate option from the desktop “file” menu. An existing M. file can be opened by
selecting “file” from menu bar and then click “Open” from desktop menu. The window editor is open
automatically when a new M. file is created or and existing M. file is opened.
1.4.6 Figure Window
A figure window is a separate window with default white background and is used to display MATLAB
graphics. The result of all the graphics command executed or displayed in the figure window. There
can be any number of figure windows depending upon the system memory. To open figure window
write “figure” in command window and press enter key. A figure window is displayed.

1.5 MATLAB Symbols with their Operations


Symbols Operations
+ Used for addition e.g. >>2+3
- Used for subtraction e.g. >>3-2
* Used for multiplication e.g. >>2*x
/ Used for division e.g. >> 2/5
^ Used for exponentiation e.g. >>2^4 →24
sqrt To find square root e.g. sqrt(4)
% Used to write comments or any statements that we do not want to execute.
pi Used for π (3.141592……)
; To terminate a line and suppress the result to display on command 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:

 Knowledge of MATLAB character set and Data types.


 Study of constants and variables and related useful functions.
 Study of functions used for conversion of Co-ordinate systems.
 Study of arithmetic, relational and logical operators.
 Knowledge of hierarchy of operations and built-in functions.
 Use of assignment statement.
2.1 Introduction
MATLAB is a powerful computing language. Programming languages process data consisting of
numbers, characters and strings and provide output, known as useful information. Data processing is
carried out by executing a sequence of instructions called a computer program. This group of
instructions or program is written by the user, using certain symbols and words according to syntax
rules of a particular language. MATLAB also has its vocabulary and grammar. In this Lab, concepts of
character set, constants, variables, data types, operators and expressions are discussed.
2.2 Character Set
It is a set of characters that form a part of the statements written using the programming language.
Characters can be broadly classified into four categories:
 Alphabets
 Numerals
 Special characters
 White space characters
MATLAB recognizes all 26 alphabets of English language. It is case-sensitive that is, upper-case letters
and lower-case letters are recognized as different characters. Numerals 0 to 9 are recognized in
MATLAB special characters.
White space characters like tab, blank, new line, vertical tab and line-feed are also included in the
character set.
2.3 Data Types
Data types are in form of array. This array is a minimum single element in size and can grow to an n-
dimensional array of any size. Two dimensional version of these arrays are called Matrices.
2.3.1 Character Data Types
Alphabets or words e.g. MATLAB is a character array. Array of strings (alphabets) can be
used to store number of strings, provided all of them have the same length that is 16 bits
long.

MATLAB MANUALS 12
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

2.3.2 Numeric Data Types


Single data type e.g. int8, int16, int32 and int64 as well as double data type e.g. uint8, uint16, uint32,
and uint64 includes signed and unsigned integer arrays that are 8, 16, 32, 64 bits in length
respectively.
2.4 Constants and Variables
Constants

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

1 𝑟𝑒𝑎𝑙(𝑥) Give real part of x

2 𝑖𝑚𝑎𝑔(𝑥) Give imaginary part of x

3 𝑐𝑜𝑛𝑗(𝑥) Produce conjugate of x , i.e 𝑥 = 𝑎 − 𝑏𝑖

4 𝑎𝑏𝑠(𝑥) Use to obtain magnitude of complex number (|𝑥| = √𝑎2 + 𝑏 2 )


𝑦
5 𝑎𝑛𝑔𝑙𝑒(𝑥) Use to obtain angle of complex numbers in radians (𝜃 = tan−1 )
𝑥

By default MATLAB accepts and return angle in radians.


2.6 Conversions of Coordinate System:
Conversion Command

[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

2.7 Character Constant:


Character constants are of following types
 Single Character constants
 String Constants
 Escape Sequence Constants
2.7.1 Single Character Constants
A single character constant contains a single character enclosed with a pair of single quote marks. Some
examples are valid single character constants are ‘y’,’g’,’1’,’_’,’ ’. It may be noted that space is also a
character.
2.7.2 String Constants:
A string constant is a sequence of characters enclosed in pair of single quotes. The characters may be
alphabets, numbers, special characters or blank space. e.g. ‘GOOD’ ‘1947’ ‘BEST WISHES’. A word
containing a single quote is specified by using two single quote together e.g. isn’t written as ‘isn’t’.
2.7.3 Escape Sequence Constants
Escape Sequence character constants are used in output functions. For example
\b Backspace
\t Tab
\n New line
\r Carriage return
\f Form feed
\\ Print back slash
\’ Print apostrophe
%% Print % or create a cell
2.8 Variables
Variables and constants form an integral form of program in any language. The different types of data
are identified by their names for case in reference. Programming languages require a programmer to
declare these variables and the type of data in advance at the beginning of program, whereas no such
declaration is required in MATLAB.
 Blank spaces cannot be included in MATLAB variables names.
 MATLAB is case-sensitive. Lower-case and upper-case latters represent two different variables
names, for example “GOLD” and “gold” are different variable names.
 Words that are reserved for the key constructs of a programming language are called
“KEYWORDS” and cannot be used as variable names. For example: for, while, switch and
functions are keywords.

MATLAB MANUALS 14
SESSSION: 2016-2020 Chemical Engineering Department
2222222020


2.9 Special Constants & Variables
Pi 3.141519

i/j √−1

Inf ∞

Ans Default output variables

2.10 Built-in Functions


The functions which are already available in MATLAB are called built-in functions. A complete list of
all MATLAB functions can be seen through Help browser. General Syntax for using these functions is:
Function_name (expression)
Built-in function Description

exp(x) Calculate 𝑒 𝑥

log(x) Calculate Natural logarithm

factorial(x) Calculate Factorial of a number

sin(x) Compute the sine of ‘x’ in radians

cos(x) Compute the cosine of ‘x’ in radians

tan(x) Compute the tangent of ‘x’ in radians

csc(x) Compute the cosecant of ‘x’ in radians

sec(x) Compute the secant of ‘x’ in radians

cot(x) Compute the cotangent of ‘x’ in radians

sind(x),cosd(x) Compute angles in degree

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]

acosh(x) Compute the inverse hyperbolic cosine of ’x’ which is equal to


ln[𝑥 + √𝑥 2 − 1]

atanh(x) Compute the inverse hyperbolic tangent of ’x’ which is

1+𝑥
equal to ln √1−𝑥 for |x|≤1

2.11 Element by element operation


We use element by element operation, when we have expressions in fractional forms.
Operations Operators Algebraic form MATLAB form

Element by element multiplication .* 𝑝×𝑞 p.*q

Element by element division ./ 𝑝/𝑞 p./q

Element by element exponentiation .^ 𝑝𝑞 p.^q

MATLAB MANUALS 16
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

2.12 ILLUSTRATIVE PROGRAMS


2.12.1 Task#1
Write a program to calculate area of circle having radius 3cm?

𝐀𝐫𝐞𝐚 𝐎𝐟 𝐂𝐢𝐫𝐜𝐥𝐞 = 𝛑𝐫 𝟐

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?

𝑪 = √𝒂𝟐 + 𝒃𝟐 − 𝟐𝒂𝒃 𝐜𝐨𝐬(𝜽)


𝟏
𝑨𝒓𝒆𝒂 𝑶𝒇 𝑻𝒓𝒊𝒂𝒏𝒈𝒍𝒆 = 𝒂𝒃 𝐬𝐢𝐧(𝜽)
𝟐
Program

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.

1- 𝒒 = 𝟐 𝐥𝐨𝐠 𝟏𝟎 𝒙 + 𝐜𝐨𝐬 𝝅 + |𝒚𝟐 − 𝒛𝟐 | + √𝟓𝒚𝒛 𝒇𝒐𝒓 𝒙 = 𝟐 , 𝒚 = 𝟒 & 𝒛 = 𝟑


𝟏
2- 𝐥𝐧(𝒙𝟐 + 𝒙 + 𝟏) 𝒘𝒉𝒆𝒓𝒆 𝒙 = 𝟐 𝒂𝒏𝒅 𝒙 = 𝟏
𝒙 𝝅 𝝅
3- 𝒘𝒉𝒆𝒓𝒆 𝒙 = 𝒂𝒏𝒅 𝒙 =
(𝒙𝟐 +𝟏)(𝐬𝐢𝐧 𝒙) 𝟒 𝟐

Program

%% q= 2log10x+cos(pi)+|y^2-z^2|+(5yz)^1/2 for x=2, y=4 & z=3


x=2;
y=4;
z=3;
q= 2*log10(x)+cos(pi)+abs(y^2-z^2)+sqrt(5*y*z)

%% ln(x^2+x+1) where x=1/2 and x=1

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

1.1920 1.1182 1.0587 1.0102 0.9698 0.9357

Columns 7 through 11

0.9065 0.8810 0.8583 0.8378 0.8188

MATLAB MANUALS 19
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

2.12.7 Task#7
Write assignment statements to evaluate the following equations:

(A) 𝑽𝒐𝒍𝒖𝒎𝒆 = 𝝅𝒓𝟐 𝒉 𝒇𝒐𝒓 𝒓 = 𝟐, 𝒉 = 𝟑


𝟐𝝅𝑵𝑻
(B) 𝑷𝒐𝒘𝒆𝒓 = 𝒇𝒐𝒓 𝑵 = 𝟏𝟎𝟎𝟎 , 𝑻 = 𝟏𝟎
𝟔𝟎

𝑽𝑰 𝐜𝐨𝐬 𝜽
(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.

3.3 Scalars and Vectors


A scalar is a 1 × 1 matrix containing a single element only. A column vector is an 𝑚 × 1 matrix that
has m-number of rows but a single column only. A row vector is a 1 × 𝑛 matrix which has n-number
of columns and has only one row.

3.4 Assigning data to elements of a Scalar/Vector


3.4.1 Row vector
In a row vector, the elements are entered with a space or a comma between the elements
inside the square brackets e.g. 𝑥 = [𝑎, 𝑏, 𝑐, 𝑑] or 𝑥 = [𝑎 𝑏 𝑐 𝑑]

3.4.2 Column vector


In a column vector, the elements are entered with a semicolon between the elements inside the square
brackets e.g. 𝑥 = [𝑎; 𝑏; 𝑐; 𝑑]

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 ;

3.5 Creation of evenly spaced Row-vectors


A row vector with evenly spaced, real elements can be created by using the following command:

𝑉𝑎𝑟𝑖𝑎𝑏𝑙𝑒_𝑛𝑎𝑚𝑒 = 𝐾: 𝐿: 𝑀

K is the initial value of the row vector


L is the step-size or increment
M is the final value of row vector
Care should be taken that the initial and final values must be appropriate. If a step-size is not specified,
+1 is taken as default value of the step-size.
3.6 Commands for Evenly Spaced Row-Vectors
linspace

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]

3.7 Built-In Functions for Handling Arrays


Some of the built-in functions available in MATLAB for managing and handling arrays are listed in table below:

Function Description Example

>> A=[5 9 2 4];


Returns the number of elements in the
length(A) >>length(A)
Vector A.
>>ans = 4

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:

Functions Description Example

mean(A) If ‘A’ is vector, returns the mean value of >>A= [3 7 2 16];


elements
>>mean(A)

>>ans = 14

c=max(A) If ‘A’ is a vector, C is the largest element in ‘A’ >>A= [3 7 2 16 9 5 18


13 0 4];

>>c=max(A)

>>c=18

[d,n]=max(A) If ‘A’ is a vector ‘d’ is the largest element in ‘A’, >>[d,n]=max(A)


‘n’ is the position of the element (the first if
several have the max value) >>d=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

std(A) If ‘A’ is a vector return the standerd derivation of >>A=[3 7 2 16];


elements of vector
>>std(A)

>>ans=6.3770

det(A) Return the determinant of a square matrix ‘A’ >>A=[3 7 2 16];

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

−5𝑥 𝑙𝑛2𝑥 + 7 sin 3𝑦


Similarly for 𝐵 = [ ]
3𝑖 5 − 13𝑖
In MATLAB: 𝐵 = [−5 ∗ 𝑥 log(2 ∗ 𝑥) + 7 ∗ sin(3 + 𝑦) ; 3∗𝑖 5 − (13 ∗ 𝑖)]

MATLAB MANUALS 25
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

3.10 Matrix Subscripts/Indices


The elements of a matrix can be specified/ accessed by specifying their respective row and column
numbers. The first index refers to the row numbers and second index refers to column number. The
elements in 𝑖𝑡ℎ row and 𝑗𝑡ℎ column of a matrix A is denoted by 𝐴(𝑖, 𝑗). For example 𝐴(2,3) refers to
the element in the second row and the third column of the matrix A.
3.11 Colon for a Matrix
The table below gives the use of a colon in addressing arrays in a matrix.
Command Description

𝐴(: , 𝑛) 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’.

3.12 Element By Element Operations


Element by element operations can only be done with arrays of the same size. Element by element
multiplication, division and exponentiation of two vectors or matrices is entered in MATLAB by typing
a period in front of arithmetic operator. Table below consist of list of these operations.

ARITHMETIC OPERATORS

Matrix Operators Arrays Operators

+ Addition + Addition

- Subtractions - Subtractions

* Multiplication .* Array Multiplication

^ Exponentiation .^ Array Exponentiation

/ Left Division ./ Array Left Division

\ Right Division .\ Array Right Division

MATLAB MANUALS 26
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

3.13 Some Useful Commands Related To Matrices


Command Description Example

det(A) It returns the determinant of a matrix (|𝐴|). >>A=[1 2; 0 4]

>>det(A)

>>ans=4

rank(A) It returns the rank of a given rectangular matrix. >>rank(A)

(no. of non-zeros rows) >>ans=2

trace(A) It returns the sum of diagonal elements of >>trace(A)


rectangular matrix.
>>ans=5

inv(A) It returns the inverse of non-singular matrix (A-1) >>inv(A)

norm(A) It returns the Euclidean norm of the given >>norm(A)


rectangular matrix ‘A’ of a given vector ‘A’
>>ans=4.4954

transpose(A) It returns the transpose of the specified >>A’


rectangular matrix.
/A’ >>ans=

1 0
2 4

3.14 Generation of Special Matrices


The following MATLAB commands and functions which generate special matrices, are often used in
engineering computation involving matrices.

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

3.15 ILLUSTRATIVE PROGRAMS


3.15.1 Task#1
𝟐
Given the row vector P = [𝟏 −𝟐 𝟓] and a column Q =[𝟒]. Solve the following:
𝟖
a) P*Q
b) Q*P
c) PT*QT
d) Sum and mean of all the components of vectors P & Q.
e) Number of elements in vectors P & Q
f) Maximum & Minimum values in vectors P & Q.
g) Product of elements of vectors P & Q.
h) Arrange the elements of vectors P & Q in ascending order.
Program

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

%% d) Sum and mean of all the components of vectors P & Q.


P=[1,-2,5];
Q=[2;4;8];
sum(P)
sum(Q)
mean(P)
mean(Q)

%% e) Number of elements in vectors P & Q.


P=[1,-2,5];
Q=[2;4;8];
length(P)
length(Q)

%% f) Maximum & Minimum values in vectors P & Q.


P=[1,-2,5];

MATLAB MANUALS 28
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

Q=[2;4;8];
max(P)
max(Q)
min(P)
min(Q)

%% g) Product of elements of vectors P & Q.


P=[1,-2,5];
Q=[2;4;8];
prod(P)
prod(Q)

%% h) Arrange the elements of vectors P & Q in ascending order.


P=[1,-2,5];
Q=[2;4;8];
sort(P)
sort(Q)
Output

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.

A=[2 -4 6 -8; 1 3 5 7; 2 12 30 56];


a=A(:,1)
% b) All the elements of first row but all columns.
A=[2 -4 6 -8; 1 3 5 7; 2 12 30 56];
b=A(1,:)
% c) Elements in the 2nd row & 3rd column.
A=[2 -4 6 -8; 1 3 5 7; 2 12 30 56];
c=A(2,3)
Output
a =

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

% Identity matrix of 3x3


eye (3,3)

% Null matrix of 3x3


zeros(3,3)

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

-0.2500 -0.5000 1.2500


0.2500 -0.5000 -0.2500
0.2500 0.5000 -0.2500

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

L=[4,3; 7,2; 4,0];


a=rank(L)

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

A=[5 -8 10 -2; 0 4 3 -4; 2 4 6 8];


B=[3 -3 -6 5; 8 0 5 4; 0 4 3 2];
A+B
A-B
A.^3
B.^4
A./B
Output

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:

 Entering data to a matrix, line continuation, matrix indices, dimension statement.


 Study of different matrix operations.
 Knowledge of special matrices.
 Study of different commands/functions used with matrices.
4.1 Introduction
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.
4.2 Matrix Manipulation
4.2.1 Reshaping matrices as a vector
All the elements of a matrix A can be grouped in to a single column vector b by the command:

𝑏 = 𝐴(: )

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.

𝑝×𝑞 =𝑚×𝑛

The command is as follows:

𝐵 = 𝑟𝑒𝑠ℎ𝑎𝑝𝑒(𝐴, 𝑚, 𝑛)

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.

4.2.3 Expanding the matrix size


When the single element or a few elements are entered in a matrix, MATLAB creates the matrix of
proper dimensions to accommodate the entered element (elements). Remaining unspecified elements
are assumed to be zero.

Commands are:

MATLAB MANUALS 37
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

 𝐴(𝑖. 𝑗) = 𝑎𝑖𝑗 (for single element)

 𝐵(𝑖. 𝑎𝑗 : 𝑏𝑗 ) = [𝑎𝑖𝑎𝑗 𝑎𝑖𝑏𝑗 ] (for ith row and specified columns)

 𝐶(𝑎𝑖 : 𝑏𝑖 , 𝑗) = [𝑎𝑎𝑖 𝑗 𝑎𝑏 𝑖 𝑗 ] (for specified rows and jth column)

4.2.4 Appending a Row/Column to a Matrix


Sometimes it is required that a column or a row to be added to a given matrix.

1. Appending Column

A column can be appended using following command:

𝐴 = [𝐴 𝑥] 𝑤ℎ𝑒𝑟𝑒 𝑥 = [𝑎; 𝑏; 𝑐]

2. Appending Row

A row can be appended using following command:

𝐴 = [𝐴 ; 𝑦] 𝑤ℎ𝑒𝑟𝑒 𝑦 = [𝑎 𝑏 𝑐]

Semicolon is used to append row. In appending rows and columns, take care of dimensions of matrix.

4.3 Deleting a Row/Column of a Matrix


Rows and Columns of a matrix can be deleted by setting the corresponding row or column vector equal
to null vector i.e. pair of empty square brackets [ ], without any element within brackets.

Commands are as follows:

 𝑨(𝒊, : ) = [ ]

It deletes all columns of 𝑖𝑡ℎ rows

 𝑨(: , 𝒋) = [ ]

It deletes all rows of 𝑗 𝑡ℎ column.

 𝑨(𝒊, 𝒋) = [ ]

This type of command will give error, because single element cannot be deleted from a matrix.

 𝑩(: , 𝒂𝒊𝒋 : 𝒃𝒊𝒋 )= [ ]

This will delete the 𝑎𝑡ℎ to 𝑏 𝑡ℎ column to all rows.

 𝑪(𝒂𝒊𝒋 : 𝒃𝒊𝒋 , : ) = [ ]

This will delete the 𝑎𝑡ℎ to 𝑏 𝑡ℎ rows to all columns.

MATLAB MANUALS 38
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

4.4 Random Numbers Generation


There are many physical processes and engineering applications that require the use of random numbers
in the development of the solution.

MATLAB has two commands that can be used to assign random numbers to variables

 The rand command

 The randn command

The rand Command

Command Description Example

Rand Generates a single random numbers between 0 and 1. >>rand

>>ans=0.9501

rand(1,n) Generates an ‘n’ elements row vector of random >>a=rand(1,3)


number between 0 and 1.
>>a=

0.4565
0.0185
0.8214
rand(n) Generates an nxn matrix with random numbers between >>b=rand(3)
0 and 1.
>>b=

0.73 0.93 0.89


0.17 0.91 0.05
0.40 0.41 0.35
rand(m,n) Generates an mxn matrix with random numbers >>c=rand(2,3)
between 0 and 1.
>>c=

0.20 0.60 0.19


0.19 0.27 0.01
randn(n) Generates an nxn matrix containing normal random
numbers with mean 0 and variance of 1.

randn(m,n) Generates an mxn matrix containing normal random


numbers with mean 0 and variance of 1.

MATLAB MANUALS 39
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

4.5 Using range within matrix


We can add equally spaced elements as much as we want in rows. This will display equally spaced
data in a matrix. Care should be taken while selecting ranges. If dimensions of each row does not
matches, it will not be executed and displays error.
Command is as follows:

𝐴 = [𝑘1 : 𝑙1 : 𝑚1 ; 𝑘2 : 𝑙2 : 𝑚2 ; 𝑘3 : 𝑙3 : 𝑚3 ; … ]

Or

𝐴 = [𝑙𝑖𝑛𝑠𝑝𝑎𝑐𝑒(𝑎1 , 𝑏1 , 𝑛) ; 𝑙𝑖𝑛𝑠𝑝𝑎𝑐𝑒(𝑎2 , 𝑏2 , 𝑛) ; 𝑙𝑖𝑛𝑠𝑝𝑎𝑐𝑒(𝑎3 , 𝑏3 , 𝑛) ; … ]

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.

4.6 Polynomials in Matrix Form


 Poly(A)

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]

This applies that the characteristic polynomial is 𝑥 2 − 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’.

4.7 ILLUSTRATIVE PROGRAMS


4.7.1 Task#1
𝟑 𝟒 𝟓 𝟔
Given 3*4 matrix Q= [𝟔 𝟕 𝟖 𝟗 ], using MATLAB commands:
𝟗 𝟏𝟎 𝟏𝟏 𝟏𝟐
a) Delete the 1st row of matrix Q.
b) Delete the 1st & 2nd column of all the rows of matrix Q.

MATLAB MANUALS 40
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

c) Extract the 2*2 sub-matrix from Q.


d) Replace the elements Q (2,2) with 800.
Program
% Delete the 1st row of matrix Q.
Q1=[3 4 5 6;6 7 8 9;9 10 11 12];
Q1(1,:)=[ ]
% Delete the 1st & 2nd column of all the rows of matrix
Q2=[3 4 5 6;6 7 8 9;9 10 11 12];
Q2(:,1:2)=[ ]
% Extract the 2*2 sub-matrix from Q.
Q3=[3 4 5 6;6 7 8 9;9 10 11 12];
Q3(2:3,2:3)
% Replace the elements Q (2,2) with 800
Q4=[3 4 5 6;6 7 8 9;9 10 11 12];
Q4(2,2)=800
Output

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

A=[2 5 6; 3 4 10; 7 11 8];


diag(A)
diag(A,2)
poly (A)
eig(A)
Output

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:

 Writing a polynomial in MATLAB


 Perform different operations on polynomials
 Generate a polynomial from given roots
 Obtain a characteristics polynomial for a given Matrix
 Compute the derivative and integration of a polynomial
 Fit a polynomial curve for a given set of point
 Evaluate polynomial with matrix argument
5.1 Introduction
A polynomial is an expression in which a finite number of constants and variables are combined using
addition subtraction multiplication and non-negative whole number exponents (raise to power). Thus
the following expressions are all considered polynomials.
 𝑥 2 + 2𝑥 − 7
 𝑥 4 − 7𝑥 3
 𝑥
The MATLAB software provides built-in functions for standard operation on polynomials such as
arithmetic operation like multiplication and division etc., evaluation of roots, differentiation, and
integration and so on. In addition there are functions for more advance applications such as curve fitting.
Polynomials have a very significant role to play in engineering system analysis. The polynomial
functions are stored in a polyfun directory in MATLAB.
5.2 Entering a Polynomial
In MATLAB, a polynomial is represented by a row vector. Polynomials are entered with variable term
arranged in descending order of its power. Only the coefficient of variable terms are entered i.e.
variables are not entered. The left most term is the highest power term of the variable and the right most
term is the constant term with variables raise to the power zero. The total number of term is always one
more than the order of the polynomial. The coefficient of polynomial is entered as an element of a row
vector and can be separated from each other by blank space or comma. For example:
𝑝(𝑥) = 𝑥 4 + 3𝑥 3 − 15𝑥 2 − 2𝑥 + 9

This can entered in MATLAB as a row vector ‘P’ as column.

𝑝 = [1 3 −15−2 9] or 𝑝 = [1,3, −15, −2,9]

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

5.3 Arithmetic Operations on Polynomials


Operations Syntax Description
X and y are two vectors for two polynomials and z
Addition of two vector is their resultant.
𝑍 =𝑥+𝑦
polynomials The dimension (size) of both polynomials vectors must
be same for addition.

For subtraction also, the size/dimensions of both vectors


Subtraction of must be same. If the number of terms of two
𝑍 =𝑥−𝑦
Two Polynomials polynomials is not equal, then zero is padded as
coefficient to make dimensions of vector same.

X and y are the vectors of coefficients of polynomials to


be multiplied and z contains the coefficient of the
𝑐𝑜𝑛𝑣(𝑥, 𝑦)
Multiplication of resultant polynomials.
Or 𝑧 =
Two Polynomials If there are more than two polynomials, then the product
𝑐𝑜𝑛𝑣(𝑥, 𝑦)
is obtained by performing multiplication of two of the
polynomials at one time.

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

5.5 ILLUSTRATIVE PROGRAMS


5.5.1 Task#1
Obtain the Values of the following Polynomials at x=-2, 4, 5 and 2+3i?
 P(x) = x2 +4x +1.
 P(x) = x2 + 1
 P(x) = x2 +4x + 2.
Program

x=[-2 , 4.5 , 2+4*i];


P1 = [1 4 1];
P2 = [1 0 1];
P3 = [1 4 2];
V1=polyval(P1,x)
V2=polyval(P2,x)
V3=polyval(P3,x)
Output

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

r1= [2; 4];


P1= poly(r1)

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

Y: 24 156 384 580 650 780

Program

n=5; % n shows Degree of Polynomial


x=[2 5 7 9 11 13];
y=[24 156 384 500 650 780];
P=polyfit(x,y,n)
x=12;
P12=polyval(P,x)
Output

P = 1.0e+003 * -0.0001 0.0048 -0.0739 0.5270


-1.6181 1.6700
P12 = 741.1275

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:

 To learn the basic features of plotting a 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 provide a legend on the plot
 To draw multiple sub-graph windows using subplot functions
 To draw specialized plots such as logarithmic, polar, bar, histogram, pie, stairs and stem plots
6.1 Introduction:
MATLAB provides very good tools for 2-dimensional plots, 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.

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:

Function Name Syntax Description

Plot plot(x , y) To draw a 2-D plot

or

plot(x,y,’style’,’linewidth’,a) Style could be line color, line style or marker


style. ‘a’ is constant for line width in cm let say
2.

Xlabel xlabel(‘string’) To label the x-axis

Ylabel ylabel(‘string’) To label the y-axis

Title title(‘string’) To give a title to the figure

Grid grid on To show the grid line on the plot

MATLAB MANUALS 53
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

Text text(‘string’) To write illustrative text on the plot

Gtext gtext(‘string’) To place text on the plot using mouse

Axis axis(‘equal’) It sets equal scale on axis

axis(‘square’) It sets rectangular frame

axis(‘normal’) It resets to default values

axis(‘off’) It turn off all axis lines, tick-marks and labels

It fits the graph in figure window.

axis tight

Legend legend(‘x’, ‘y’, ‘z’) To produce a boxed legend on the plot

Subplot subplot(r , c , l) To subdivide graphic window into many sub-


graphs.
or
Use this command before ‘plot’ command
subplot rcl

r=number of rows

c=number of columns

l=location of subplot on
figure window

Axis axis([𝑥𝑎 𝑥𝑏 𝑦𝑎 𝑦𝑏 ]) To fix range of points on axis

Pause pause(n) To fix the time in seconds for drawing multiple


graphs
n=number of seconds

Hold hold on Use plot command and then hold command to


plot multiple graphs on single axis

Line line(x , y) Use it after plot command to draw multiple


graphs on single axis.

MATLAB MANUALS 54
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

2. 2-D Plot Functions:


Function name Description

𝑠𝑒𝑚𝑖 𝑙𝑜𝑔 𝑥 (𝑥, 𝑦) Plot with logarithmic scale x-axis and linear scale y-axis

𝑠𝑒𝑚𝑖 𝑙𝑜𝑔 𝑦 (𝑥, 𝑦) Plot with linear scale x-axis and logarithmic scale y-axis

𝑙𝑜𝑔 𝑙𝑜𝑔(𝑥, 𝑦) Plot with logarithmic scale x-axis and y-axis

𝑝𝑜𝑙𝑎𝑟(𝜃, 𝑟) To draw a plot on polar axis coordinates

𝑎𝑟𝑒𝑎(𝑥, 𝑦) Same as ‘plot’ command except area under curve is filled with color

𝑠𝑡𝑎𝑖𝑟𝑠(𝑥, 𝑦, ′𝑠𝑡𝑦𝑙𝑒′) To give stair case plot

𝑐𝑜𝑛𝑡𝑜𝑢𝑟(𝑥, 𝑦, ′𝑠𝑡𝑦𝑙𝑒′) To give contour of the given matrix

6.3 Style Options


1. Color Style Options:

y = yellow m = magenta c = cyan

r = red g = green b = blue

w = white k = black

2. Marker Style Options:

. = point o = circle x = x-mark

+ = plus * = star s = square

d = diamond v = triangle (down) h = hexagram

^ = triangle (up) < = triangle (left)

> = triangle (right) p = pentagram

3. Line Style Options


For Solid line= - For Dashed line= --
For Dotted line= . For Dashed dotted line= -.

MATLAB MANUALS 55
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

6.4 ILLUSTRATIVE PROGRAMS


6.4.1 Task#01
Plot a curve for the equation
𝒚 = 𝒙𝟑 + 𝟐𝒙𝟐 − 𝟓 , −𝟏𝟎 < 𝒙 < 𝟏𝟎.
Use labels, title and gtext command to write this equation on the curve plotted?
Program

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,y1, 'r-o','linewidth',2)


pause (2)

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

title('y Versus x');

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

Graphing stairs plot using stairs Command


4

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

Graphing stairs plot using stairs Command


8

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

Graphing stairs plot using stairs Command


6

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:

 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 in 3D graphs.
7.1 Introduction
MATLAB provides very good tools for 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 axes, changing line colors and markers, adding annotation and legends.

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.

7.2 List of 3D Graphic Commands


Function Description

𝑝𝑙𝑜𝑡3(𝑥, 𝑦, 𝑧) To plot a simple 3D plot.

[𝑋, 𝑌] = 𝑚𝑒𝑠ℎ𝑔𝑟𝑖𝑑(𝑥, 𝑦) To give array for mesh grid

𝑚𝑒𝑠ℎ(𝑥, 𝑦, 𝑧) To plot wireframe mesh plot

𝑠𝑢𝑟𝑓(𝑥, 𝑦, 𝑧) To plot surface plot

𝑚𝑒𝑠ℎ𝑐(𝑥, 𝑦, 𝑧) To show shadow or circles beneath graph

𝑚𝑒𝑠ℎ𝑧(𝑥, 𝑦, 𝑧) To show curtons beneath graph

𝑠𝑢𝑟𝑓𝑐(𝑥, 𝑦, 𝑧) To plot shadow beneath surface

𝑐𝑜𝑛𝑡𝑜𝑢𝑟3(𝑥, 𝑦, 𝑧) To give contour over the plane

𝑤𝑎𝑡𝑒𝑟𝑓𝑎𝑙𝑙(𝑥, 𝑦, 𝑧) To show lines of 3D graph like waterfall

𝑠𝑡𝑒𝑚3(𝑥, 𝑦, 𝑧) To draw the discrete surface as stems

𝑐𝑜𝑚𝑒𝑡3(𝑥, 𝑦, 𝑧) To see graph while drawing

MATLAB MANUALS 66
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

7.3 ILLUSTRATIVE PROGRAMS


7.3.1 Task#01
Given is 𝒚 = 𝐬𝐢𝐧 𝒙 𝒂𝒏𝒅 𝒛 = 𝒙 + 𝟓 , 𝒇𝒐𝒓 𝟎 < 𝒙 < 𝟓𝟎𝟎𝟎
Obtain a 3D plot showing the matrix is (y,z) space as a factors of ‘x’?
Program

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

Use of stem3 Command

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

𝑏𝑎𝑟(𝑥, 𝑦,′ 𝑠𝑡𝑦𝑙𝑒 𝑜𝑝𝑡𝑖𝑜𝑛′ ) To draw vertical bar-graph


Style options means colors of bins
Or Grouped means multiple bar graph and stacked means simple
𝑏𝑎𝑟(𝑥, 𝑦,′ 𝑔𝑟𝑜𝑢𝑝𝑒𝑑 𝑜𝑟 𝑠𝑡𝑎𝑐𝑘𝑒𝑑′) bar graph

𝑏𝑎𝑟ℎ(𝑥, 𝑦) To draw horizontal bar-graph

ℎ𝑖𝑠𝑡(𝑥, 𝑦) To draw histogram

𝑝𝑖𝑒(𝑥, 𝑦) To draw pie plot

𝑠𝑡𝑒𝑚(𝑥, 𝑦) To draw a stem plot

𝑟𝑜𝑠𝑒(𝑥, 𝑦) To draw a histogram in polar form

𝑏𝑎𝑟3(𝑥, 𝑦) To plot a 3D vertical bar graph

𝑏𝑎𝑟3ℎ(𝑥, 𝑦) To plot a 3D horizontal bar graph

𝑝𝑖𝑒3(𝑥, 𝑦) To plot a 3D pie plot

MATLAB MANUALS 72
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

8.3 ILLUSTRATIVE PROGRAMS


8.3.1 Task#01
Plot the bar graph for the data given as:
𝒙 = [𝟎 𝟏 𝟐 𝟑 𝟒 𝟓 𝟔] 𝒂𝒏𝒅 𝒚 = [𝟏𝟎 𝟏𝟓 𝟐𝟓 𝟐𝟎 𝟑𝟎 𝟐𝟕 𝟏𝟗]?
Program

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:

MONTHS CITY A CITY B CITY C


September 31 28 24
October 29 26 22
November 28 25 20
December 27 24 16
January 26 22 17
February 29 25 20
Program

x= [31,28,24; 29,26,22; 28.25,20; 27,24,16; 26,22,17; 29,25,20];


bar(x, 'grouped') % grouped/stacked
xlabel('Months from September to February');

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

Comparison of Average Temperature in City A, B and C


35
City A
City B
30
City C

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

X=randn(500,1)*pi; % generate 500 random data points


P=-pi:0.5:pi; % specifies the number of bins in a vector V
rose (x,P)
title ('Polar Histogram using Rose Function');
Output

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?

Professions No. of Persons


Manager 12
Engineer 15
Professor 13
Doctor 11
Architect 6
Designer 10
Program

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:

 To learn conditional and unconditional flow control structures in MATLAB.


 Looping control structures.
 Branding control structures.
 Special MATLAB statements which control program execution sequence.
9.1 Introduction
The instruction given in a program are executed in a sequence in which they are written, however many
times program applications demands that the sequence of execution of the instruction be changed or a
group of instruction can be repeated depending upon some conditions, control structure are provided in
a computer language to make care of such needs of the program, use for testing a condition for true or
false, repeated execution of statements out of several different available possibilities.
Like other programming language, the MAT-Lab also has different control structures for controlling
the sequence of execution of statement of a program.
 First there is a conditional execution in which a condition is checked and then action is taken as
per the result of the condition. In another type of control structure instructions are executed
repeatedly until some conditions is met. This is called Conditional looping, no of repetitions are
not known.
 A group of instructions are executed repeatedly foe specified no of times are called
unconditional looping and in this case no of repetitions are already known.
Control structures are also available for selective execution of group of instructions, to solve such type
of executions; MAT-Lab has a number of control structures. There are 2 broad categories of these
control structures.

9.2 LOOPING STRUCTURES


They cause specific group of instructions to be repeated for a fixed no of times or until the given
condition is specified, some of looping structures are for, while among others.

9.3 BRANCHING STRUCTURES


They select the specific blocks of the program for execution depending upon the condition satisfied,
some of them are if, if-else among others.
Beside, these there are some other commands such as break, error; continue to control the execution
of such structures.

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.

9.5 FOR LOOP


It is used for unconditional looping, in it a group of statements say ‘n’ in no are executed for a fixed
no of times, which are known before the loop starts and is decided by an index, its syntax are as follows:
for index = expression
statement # 1;
statement # 2;
.........................
statement # n;
end
next statement;
The index is assigned an initial value and then a group of statements are executed till ‘end’ statement.
After completion of one loop the index is incremented by specifying and again group of statements are
executed until the provided value of index not exceeds the last value. Then loop is terminated.
9.6 NESTED FOR LOOP
When a for loop is embedded in another for loop, the 2 loops are called nested for loops. The
necessary condition is that one loop is completely nested in 2nd loop.
9.7 WHILE LOOP
It is used for executing a group of statements repeatedly on the basis of condition. In this loop
the group of statements associated with the while statement are executed infinitely until the condition
true, its general form are:

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.

9.8 BRANCHES CONTROL STRUCUTRE


They allow selection and execution of some specific statements depending upon the condition
They include if, if-else and switch etc. If is the conditional statement which allow some group of
statements to be executed if the given condition is true.

MATLAB MANUALS 79
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

9.9 IF CONTROL STRUCTURE


In if control structure a group of statements are executed only if the condition is true, some are given
blow:
 If structure.
 If-else structure.
 If-else, if-else structure.
 Nested if structure.
9.10 IF STRUCUTRE
This is simplest form of structure, it has only 1 group of statements which is executed if the condition
is true otherwise not, its syntax is:
If (expression)
statement # 1;
statement # 2;
........................
statement # n;
end

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.

9.11 IF-ELSE STRUCUTRE


In this form control structure has 2 statements if or else one for true and other for false, its syntax is as
follows:

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

9.12 IF-ELSE-IF STRUCTURE


It is most use of if structure and it allow the user to check large no of statements and expressions. Its
syntax is as follows:
If (expression)
statement # 1;
statement # 2;
........................
statement # n;
else if (expression)
statement # 1;
statement # 2;
........................
statement # n;
else
statement # 1;
statement # 2;
........................
statement # n;
end
next statement;
 If the expression give true condition then all of its statements are run and other all are skipped
or if it give false then after end statements are run and if statements are skipped.
 There are some multiple blocks in if else if else structure, the if else condition is tested
sequentially if the previous condition are false, once the true statement is found then at block is
executed and other all statements are skipped.
9.13 NESTED IF STRUCTURE
Like other control structures, if structure can also be nested if structure are called nested, when1 of the
“if structure” lies entirely within in the domain of other if structure, its syntax is:
If (condition)
statement # 1;
statement # 2;
If (condition)
statement # 1;
statement # 2;
end
statement # 1;
statement # 2;
end

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

3. Now check the following


a) If f ( x ) f ( xm )  0 , then the root lies between x and xm ; then x  x and xu  xm .
b) If f ( x ) f ( xm )  0 , then the root lies between xm and xu ; then x  xm and xu  xu
c) If f ( x ) f ( xm )  0 ; then the root is xm . Stop the algorithm if this is true.
4. Find the new estimate of the root
x  xu
xm = 
2

Find the absolute relative approximate error as

xmnew - xmold
a =  100
xmnew

where

xmnew = estimated root from present iteration

xmold = estimated root from previous iteration

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

A mass balance for a pollutant in a well-mixed lake can be written as:

𝒅𝒄
𝒗 = 𝒘 − 𝑸𝒄 − 𝒌𝒗√𝒄
𝒅𝒕
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

f=@(x) 25*sqrt(x)+10*x-100 % Let steady-state concentration = x


f(0)
f(5)
f(10)
fplot(f,[0,10])
xlabel('Steady-state concentration, c');
ylabel('f(c)');
title('BI-SECTION METHOD');
gtext('xr')
grid on

xa=0; % Initial guess


xb=5; % Initial guess

fprintf ('i xa xb xr f(xr) RE\n');

for i=1:20
xr=(xa+xb)/2; % Bisection formula

f_xr=25*sqrt(xr)+10*xr-100;
RE=abs((xr-xb)/xr)*100;

fprintf ('%6d %15.5f %15.5f %15.5f %15.5f %18.5f \n' ,


i,xa,xb,xr,f_xr,RE);

if f(xr)*f(xa)<0 % Root Bracketing


xb=xr;
xa=xa;

else
xa=xr;
xb=xb;

end %End of if-else Statement


end %End of For-Loop Statement
fprintf('\n The root of given equation = %f \n' , xr); % to print
statement

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

The root of given equation = 4.624085

MATLAB MANUALS 85
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

Graph

10.3 REGULA-FALSI METHOD


ALGORITHM

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 .

Estimate the root, x r of the equation f x   0 as

xU f x L   x L f xU 
xr 
f x L   f xU 

Now check the following

If f x L  f xr   0 , then the root lies between x L and xr ; then x L  x L and xU  xr .

If f x L  f xr   0 , then the root lies between xr and xU ; then x L  x r and xU  xU .

If f x L  f xr   0 , then the root is x r . Stop the algorithm.

Find the new estimate of the root

xU f x L   x L f xU 
xr 
f x L   f xU 

MATLAB MANUALS 86
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

Find the absolute relative approximate error as

x rnew  x rold
a   100
x rnew

where

x rnew = estimated root from present iteration

xrold = estimated root from previous iteration

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!

10.4 MATLAB CODE


10.4.1 Task

A mass balance for a pollutant in a well-mixed lake can be written as:

𝒅𝒄
𝒗 = 𝒘 − 𝑸𝒄 − 𝒌𝒗√𝒄
𝒅𝒕
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

f=@(x) 25*sqrt(x)+10*x-100 % Let steady-state concentration = x


f(0)
f(5)
f(10)
fplot(f,[0,10])
xlabel ('Steady-state concentration, c');
ylabel ('f(c)');
title ('REGULA-FALSI METHOD');
grid on
gtext('xr');

xa=0; % Initial guess


xb=10; % Initial guess

fprintf ('i xa xb xr f(xr) RE\n');

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;

fprintf ('%6d %15.5f %15.5f %15.5f %15.5f %18.5f \n' ,


i,xa,xb,xr,f_xr,RE);

if f(xr)*f(xa)<0 % Root Bracketing


xb=xr;
xa=xa;

else
xa=xr;
xb=xb;

end %End of if-else Statement


end %End of For-Loop Statement
fprintf('\n The root of given equation = %f \n' , xr); % to print
statement
Output

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:

 How does Open Methods work?


 Background of Open Methods.
 Algorithm.
 Convergence sheet.
11.1 NEWTON-RAPHSON METHOD
ALGORITHM

The steps of the Newton-Raphson method to find the root of an equation f x   0 are

1. Evaluate f x  symbolically


2. Use an initial guess of the root, xi , to estimate the new value of the root, xi 1 , as
f xi 
xi 1 = xi 
f xi 

3. Find the absolute relative approximate error a as


xi 1  xi
a =  100
xi 1

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.

11.2 MATLAB CODE


11.2.1 Task
A mass balance for a pollutant in a well-mixed lake can be written as:

𝒅𝒄
𝒗 = 𝒘 − 𝑸𝒄 − 𝒌𝒗√𝒄
𝒅𝒕
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');

xa=10; % Initial Guess

fprintf ('i xa xr f(xr) RE\n');

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

end %End of For-Loop Statement

fprintf('The root of given equation = %f \n' , xr);


Output

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

2 4.62232 4.62232 -0.02787 6.23770

3 4.62408 4.62408 -0.00000 0.03812

4 4.62408 4.62408 0.00000 0.00000

5 4.62408 4.62408 0.00000 0.00000

The root of given equation = 4.624081

Graph

11.3 SECANT METHOD


ALGORITHM

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

Substituting Equation (2) in Equation (1) gives

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

11.4 MATLAB CODE


11.4.1 Task

A mass balance for a pollutant in a well-mixed lake can be written as:

𝒅𝒄
𝒗 = 𝒘 − 𝑸𝒄 − 𝒌𝒗√𝒄
𝒅𝒕
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

f=@(x) 25*sqrt(x)+10*x-100 % Let steady-state concentration = x


f(0)
f(5)
f(10)
fplot(f,[0,10])
xlabel ('Steady-state concentration, c');
ylabel ('f(c)');
title ('Secant METHOD');
grid on
gtext('xr');

xa=0;
xb=10;
f_xa=@(x) 25*sqrt(xa)+10*xa-100;
f_xb=@(x) 25*sqrt(xb)+10*xb-100;

fprintf ('i xa xb xr f(xr) RE\n');

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

fprintf ('%6d %15.7f %15.7f %15.7f %15.7f %18.8f \n' ,


i,xa,xb,xr,f_xr,RE);
xa=xb;
f_xa=f_xb;

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

1 0.0000000 10.0000000 5.5848156 14.9286921


100.000000

2 10.00000 5.5848156 4.5569858 -1.0623985


119.4433017

3 5.5848156 4.5569858 4.6252716 0.0188273


20.74567944

4 4.5569858 4.6252716 4.6240825 0.0000253


1.45102891

5 4.6252716 4.6240825 4.6240809 -0.0000000


0.02574892

6 4.6240825 4.6240809 4.6240809 -0.0000000


0.00003454

7 4.6240809 4.6240809 4.6240809 0.0000000


0.00000000

8 4.6240809 4.6240809 4.6240809 0.0000000


0.00000000

The root of given equation = 4.624081

MATLAB MANUALS 95
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

Graph

11.5 FIXED POINT ITERATION METHOD


ALGORITHM

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.

11.6 MATLAB CODE


11.6.1 Task

A mass balance for a pollutant in a well-mixed lake can be written as:

𝒅𝒄
𝒗 = 𝒘 − 𝑸𝒄 − 𝒌𝒗√𝒄
𝒅𝒕
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

f=@(x) 25*sqrt(x)+10*x-100 % Let steady-state concentration = x


g=@(x) 10-2.5*sqrt(x);
f(0)
f(5)
f(10)
fplot(f,[0,10])
xlabel('Steady-state concentration, c');
ylabel('f(c)');
title('FIXED-POINT ITERATION METHOD');
grid on
gtext('xr');

xa=0; % Initial guess

fprintf('i xa xr g_xr RE \n');

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

2 10.0000000 2.0943058 6.3820708 377.4851773

3 2.0943058 6.3820708 3.6843098 67.1845407

4 6.3820708 3.6843098 5.2013610 73.2229686

5 3.6843098 5.2013610 4.2983769 29.1664276

6 5.2013610 4.2983769 4.8168682 21.0075604

7 4.2983769 4.8168682 4.5131588 10.7640749

8 4.8168682 4.5131588 4.6889509 6.7294187

9 4.5131588 4.6889509 4.5865036 3.7490704

10 4.6889509 4.5865036 4.6459690 2.2336682

11 4.5865036 4.6459690 4.6113725 1.2799356

12 4.6459690 4.6113725 4.6314734 0.7502439

13 4.6113725 4.6314734 4.6197854 0.4340064

14 4.6314734 4.6197854 4.6265785 0.2529973

15 4.6197854 4.6265785 4.6226293 0.1468258

16 4.6265785 4.6226293 4.6249248 0.0854305

17 4.6226293 4.6249248 4.6235904 0.0496329

18 4.6249248 4.6235904 4.6243661 0.0288607

19 4.6235904 4.6243661 4.6239152 0.0167735

20 4.6243661 4.6239152 4.6241773 0.0097514

21 4.6239152 4.6241773 4.6240249 0.0056681

22 4.6241773 4.6240249 4.6241135 0.0032950

23 4.6240249 4.6241135 4.6240620 0.0019153

24 4.6241135 4.6240620 4.6240919 0.0011134

MATLAB MANUALS 98
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

25 4.6240620 4.6240919 4.6240745 0.0006472

26 4.6240919 4.6240745 4.6240846 0.0003762

27 4.6240745 4.6240846 4.6240788 0.0002187

28 4.6240846 4.6240788 4.6240822 0.0001271

29 4.6240788 4.6240822 4.6240802 0.0000739

30 4.6240822 4.6240802 4.6240814 0.0000430

31 4.6240802 4.6240814 4.6240807 0.0000250

32 4.6240814 4.6240807 4.6240811 0.0000145

33 4.6240807 4.6240811 4.6240808 0.0000084

34 4.6240811 4.6240808 4.6240810 0.0000049

35 4.6240808 4.6240810 4.6240809 0.0000029

36 4.6240810 4.6240809 4.6240809 0.0000017

37 4.6240809 4.6240809 4.6240809 0.0000010

38 4.6240809 4.6240809 4.6240809 0.0000006

39 4.6240809 4.6240809 4.6240809 0.0000003

40 4.6240809 4.6240809 4.6240809 0.0000002

41 4.6240809 4.6240809 4.6240809 0.0000001

42 4.6240809 4.6240809 4.6240809 0.0000001

43 4.6240809 4.6240809 4.6240809 0.0000000

44 4.6240809 4.6240809 4.6240809 0.0000000

45 4.6240809 4.6240809 4.6240809 0.0000000

The root of given equation = 4.624081

MATLAB MANUALS 99
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

Graph

MATLAB MANUALS 100


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

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

Given a general set of n equations and n unknown’s, we have:


a11x1 + a12x2 + a13x3 + ...................... + a1nxn = c1.
a21x1 + a22x2 + a23x3 + ..................... + a2nxn = c2.
............................................................................
............................................................................
............................................................................
an1x1 + an2x2 + an3x3 + ...................... + ann xn = cn.

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.

Generally, iterative form of method is:


x1(i+1) = (c1 - a12x2i - a13x3 i - ...................... - a1nxn i ) / a11.
x2(i+1) = (c2 - a21x1i - a23x3i - ...................... - a2nxni) / a22.
x3 (i+1) = (c3 – a31x1i – a32x2i - ...................... - a3nxni) / a33.
...............................................................................
...............................................................................
xn(i+1) = (cn – an1x1i – an2x2i - ...................... - an,n-1xn-1i) / an-1.

Also find the absolute relative error:


R.E=|((present value-Previous value)/ present value) | * 100.

MATLAB MANUALS 101


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

12.2 MATLAB CODE


12.2.1 Task
Solve the given system of equations using Jacobi's Method on MATLAB?
𝟑𝒙𝟏 − 𝟎. 𝟏𝒙𝟐 − 𝟎. 𝟐𝒙𝟑 = 𝟕. 𝟖𝟓
𝟎. 𝟏𝒙𝟏 − 𝟕𝒙𝟐 − 𝟎. 𝟑𝒙𝟑 = −𝟏𝟗. 𝟑
𝟎. 𝟑𝒙𝟏 − 𝟎. 𝟐𝒙𝟐 − 𝟏𝟎𝒙𝟑 = 𝟕𝟏. 𝟒
Program
%%
clc
clear all
close all

a11=3; a12=-0.1; a13=-0.2;


a21=0.1; a22=7; a23=-0.3;
a31=0.3; a32=-0.2; a33=10;

b1 = 7.85; b2=-19.3; b3=71.4;

x(1)=0; % Initial Guess


y(1)=0; % Initial Guess
z(1)=0; % Initial Guess

fprintf('i x(i+1) y(i+1) z(i+1) REx REy REz \n');

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;

fprintf ('%6d %15.5f %15.5f %15.5f %15.5f %15.5f %15.5f


\n', i, x(i+1) , y(i+1) , z(i+1) , REx , REy, REz);
end

fprintf('\n x = % f' , x(i+1));


fprintf('\n y = % f' , y(i+1));
fprintf('\n z = % f\n' , z(i+1));
% to plot system of equations
X = [-20:20];
Y = [-20:20];
[x,y] = meshgrid (X,Y);

z1 = (b1 - a11*x - a12*y)/a13;


z2 = (b2 - a21*x - a22*y)/a23;
z3 = (b3 - a31*x - a32*y)/a33;
mesh(x,y,z1)
hold on
mesh (x,y,z2)

MATLAB MANUALS 102


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

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

i x(i+1) y(i+1) z(i+1) REx REy REz


1 2.61667 -2.75714 7.14000 100.00000 100.00000 100.0000
2 3.00076 -2.48852 7.00636 12.79992 10.79431 1.90745
3 3.00081 -2.49974 7.00021 0.00148 0.44863 0.08786
4 3.00002 -2.50000 6.99998 0.02613 0.01057 0.00322
5 3.00000 -2.50000 7.00000 0.00079 0.00006 0.00026
6 3.00000 -2.50000 7.00000 0.00004 0.00004 0.00001
7 3.00000 -2.50000 7.00000 0.00000 0.00000 0.00000
8 3.00000 -2.50000 7.00000 0.00000 0.00000 0.00000
9 3.00000 -2.50000 7.00000 0.00000 0.00000 0.00000
10 3.00000 -2.50000 7.00000 0.00000 0.00000 0.00000

x = 3.000000
y = -2.500000
z = 7.000000
Graph

________________________________________________________________________________________

MATLAB MANUALS 103


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

12.3 GUASS-SEIDEL METHOD


ALGORITHM

Given a general set of n equations and n unknown’s, we have:


a11x1 + a12x2 + a13x3 + ...................... + a1nxn = c1.
a21x1 + a22x2 + a23x3 + ..................... + a2nxn = c2.
............................................................................
............................................................................
an1x1 + an2x2 + an3x3 + ...................... + annxn = cn.

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.

Iterative form of method is:


x1(i+1) = (c1 - a12x2i - a13x3 i - ...................... - a1nxn i ) / a11.
x2(i+1) = (c2 - a21x1i+1 - a23x3i - ...................... - a2nxni) / a22.
x3 (i+1) = (c3 – a31x1i+1 – a32x2i+1 - ...................... - a3nxni) / a33.
...............................................................................
...............................................................................
xn(i+1) = (cn – an1x1i+1 – an2x2i+1 - ...................... - an,n-1xn-1i+1) / an-1.
Also find the absolute relative error:
R.E=|((present value-Previous value)/ present value) | * 100.

12.4 MATLAB CODE


12.4.1 Task
Solve the given system of equations using Gauss Seidel Method on MATLAB?
𝟑𝒙𝟏 − 𝟎. 𝟏𝒙𝟐 − 𝟎. 𝟐𝒙𝟑 = 𝟕. 𝟖𝟓
𝟎. 𝟏𝒙𝟏 − 𝟕𝒙𝟐 − 𝟎. 𝟑𝒙𝟑 = −𝟏𝟗. 𝟑
𝟎. 𝟑𝒙𝟏 − 𝟎. 𝟐𝒙𝟐 − 𝟏𝟎𝒙𝟑 = 𝟕𝟏. 𝟒
Pragram

clc
clear all
close all

a11=3; a12=-0.1; a13=-0.2;


a21=0.1; a22=7; a23=-0.3;

MATLAB MANUALS 104


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

a31=0.3; a32=-0.2; a33=10;

b1 = 7.85; b2=-19.3; b3=71.4;

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;

fprintf ('%6d %15.5f %15.5f %15.5f %15.5f %15.5f %15.5f


\n', i, x(i+1) , y(i+1) , z(i+1) , REx , REy, REz);
end

fprintf('\n x = % f' , x(i+1));


fprintf('\n y = % f' , y(i+1));
fprintf('\n z = % f \n' , z(i+1));

X = [0:20];
Y = [0:20];
[x,y] = meshgrid (X,Y);

z1 = (b1 - a11*x - a12*y)/a13;


z2 = (b2 - a21*x - a22*y)/a23;
z3 = (b3 - a31*x - a32*y)/a33;

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

% Shortcut method: x=inv(A)*B;

MATLAB MANUALS 105


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

Output

i x(i+1) y(i+1) z(i+1) REx REy REz


1 2.61667 -2.79452 7.00561 100.00000 100.00000 100.00000
2 2.99056 -2.49962 7.00029 12.50235 11.79774 0.07598
3 3.00003 -2.49999 7.00000 0.31584 0.01453 0.00416
4 3.00000 -2.50000 7.00000 0.00105 0.00048 0.00001
5 3.00000 -2.50000 7.00000 0.00001 0.00000 0.00000
6 3.00000 -2.50000 7.00000 0.00000 0.00000 0.00000

x = 3.000000
y = -2.500000
z = 7.000000

Graph

MATLAB MANUALS 106


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

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.

13.2 MATLAB CODE


13.2.1 Task
Illustrate the implementation of Lagrange Interpolation method using MATLAB code for the
given set of points:

𝑻: 0 8 16 24 32 40
𝑶(𝑻): 14.621 11.843 9.870 8.418 7.305 6.413

Estimate 'O' at T=27?

MATLAB MANUALS 107


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

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

% Given unknown x whose value has to be interpolated.


xa=27;
ya=0; % initializing y

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

% To fit the polynomial


fx=polyfit(x,y,5)

% To plot the curve for the given data.


xnew=[0,8,16,24,xa,32,40];
ynew=[14.621,11.843,9.870,8.418,ya,7.305,6.413];
fprintf('The value of y at x=27 is: %f',ya);
plot(xnew,ynew,'k-',xa,ya,'ro','linewidth',2)
xlabel('x-values');
ylabel('y-values');
title('Lagrange Interpolation');
gtext('Interpolating point');
grid on

% To find the Error


exact=7.986;
RE=(abs((exact-ya)/exact))*100;
fprintf('\n Percentage Relative Error=%f \n',RE);
%%
% shortcut method
x=[12,13,14,15,16];
y=[5,6,9,11.5,11];
xa=15;
p=polyfit(x,y,3)
ya=polyval(p,xa)
plot(x,y,'k-',xa,ya,'ro')
MATLAB MANUALS 108
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

Output

fx =

-0.0000 0.0000 -0.0002 0.0095 -0.4135 14.6210

The value of y at x=27 is: 7.968239

Percentage Relative Error = 0.222402

Graph

Lagrange Interpolation
16

14
y-values

12

Interpolating point
10

6
0 10 20 30 40
x-values

13.3 NEWTON DIVIDED DIFFERENCE INTERPOLATION METHOD:


ALGORITHM

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

MATLAB MANUALS 109


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

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 )

the second divided difference by

f ( x1 )  f ( x0 )
f [ x1 , x0 ] 
x1  x0

and the third divided difference by

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

where f [ x0 ], f [ x1 , x0 ], and f [ x2 , x1 , x0 ] are called bracketed functions of their variables enclosed in


square brackets.

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 ,......,xn1 , yn1 , xn , yn  , as

f n ( x)  b0  b1 ( x  x0 )  ....  bn ( x  x0 )( x  x1 )...(x  xn1 )

where

b0  f [ x0 ]

b1  f [ x1 , x0 ]

b2  f [ x2 , x1 , x0 ] ……

bn1  f [ xn1 , xn2 ,....,x0 ]

bn  f [ xn , xn1 ,....,x0 ]

where the definition of the mth divided difference is

MATLAB MANUALS 110


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

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.

13.4 MATLAB CODE


13.4.1 Task
Illustrate the implementation of Lagrange Interpolation method using MATLAB code for the
given set of points:

𝑻: 0 8 16 24 32 40
𝑶(𝑻): 14.621 11.843 9.870 8.418 7.305 6.413

Estimate 'O' at T=27?


Program

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

MATLAB MANUALS 111


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

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

Newtons Divided difference table:


D=
14.6210 0 0 0 0 0
11.8430 -0.3473 0 0 0 0
9.8700 -0.2466 0.0063 0 0 0
8.4180 -0.1815 0.0041 -0.0001 0 0
7.3050 -0.1391 0.0026 -0.0001 0.0000 0
6.4130 -0.1115 0.0017 -0.0000 0.0000 -0.0000
ya=8.023250
exact value=7.96820
Percentage Relative Error=0.690871

MATLAB MANUALS 112


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

14 LAB#14
DEMONSTRATION AND MANIPULATION OF
NUMERICAL INTEGRATION BY TRAPEZOIDAL RULE
AND SIMPSON’S 1/3 RULE
The learning objectives are:

 How does Trapezoidal rule and Simpson rule work?


 Background.
 Algorithms.
 Convergence Sheet.
14.1 TRAPEZOIDAL RULE
ALGORITHM

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

ba
h .
n

Now
b xn

 f ( x)dx   f ( x)dx
a x0

where

x0  a xn  b

b x2 x4 xn  2 xn

 f ( x)dx   f ( x)dx   f ( x)dx  ......  f ( x)dx   f ( x)dx


a x0 x2 xn  4 xn  2

Apply Trapezoidal Rule over each interval, we get:

𝑏 𝑛−1
(𝑏 − 𝑎)
∫ 𝑓(𝑥)𝑑𝑥 = (𝑓(𝑥0 ) + 𝑓(𝑥𝑛 ) + 2 ∑ 𝑓(𝑥𝑖 ))
𝑎 2𝑛
𝑖=1

MATLAB MANUALS 113


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

14.2 MATLAB CODE


14.2.1 Task
Integrate the given integral using Trapezoidal Rule in MATLAB. Use 10 segments with step-
size of ‘h’ to approximate the integral.
𝟎.𝟖

𝑰 = ∫ (𝟎. 𝟐 + 𝟐𝟓𝒙 − 𝟐𝟎𝟎𝒙𝟐 + 𝟔𝟕𝟓𝒙𝟑 − 𝟗𝟎𝟎𝒙𝟒 + 𝟒𝟎𝟎𝒙𝟓 ) 𝒅𝒙


𝟎

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;

y=0; % Initializing the point for loop


x=a; % Initializing 'x' point

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

I2=(h*(feval(f,a)+feval(f,b))/2); % Area of yo and yn


I=I1+I2; % Total Area

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

MATLAB MANUALS 114


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

Graph

Finding area using Trapezoidal rule


4

2
f(x)

Area under curve


0

-1

-2
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
x

14.3 SIMPSONS 1/3 RULE


ALGORITHM:

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

ba
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 ( x)dx   f ( x)dx   f ( x)dx  ......  f ( x)dx   f ( x)dx


a x0 x2 xn  4 xn  2

Apply Simpson’s 1/3rd Rule over each interval,

 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   ...

MATLAB MANUALS 115


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

 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 ) 
 ( xn2  xn4 )    ( xn  xn2 ) 
 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 ( xn1 )  2 f ( x2 )  f ( x4 )  ...  f ( xn2 )  f ( xn )
3

 n 1 n2

h
 f ( x 0 )  4  f ( xi )  2  f ( xi )  f ( x n ) 
3 i 1 i 2

 i  odd i  even 

 
ba  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 

14.4 MATLAB CODE


14.4.1 Task
Integrate the given integral using Simpsons 1/3 Rule in MATLAB. Use 10 segments with step-size
of ‘h’ to approximate the integral.
𝟎.𝟖

𝑰 = ∫ (𝟎. 𝟐 + 𝟐𝟓𝒙 − 𝟐𝟎𝟎𝒙𝟐 + 𝟔𝟕𝟓𝒙𝟑 − 𝟗𝟎𝟎𝒙𝟒 + 𝟒𝟎𝟎𝒙𝟓 ) 𝒅𝒙


𝟎

Program

% Simpsons 1/3 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 Simpsons 1/3 rule');
gtext('Area under curve');
MATLAB MANUALS 116
SESSSION: 2016-2020 Chemical Engineering Department
2222222020

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

Finding area using Simpsons 1/3 rule


4

2
f(x)

0 Area under curve

-1

-2
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
x

MATLAB MANUALS 117


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

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 algorithm for the method is as follows:

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)

Substituting eq(1) in eq(2):


𝑦𝑖+1 = 𝑦𝑖 + [𝑓(𝑡𝑖 , 𝑦𝑖 ) + 𝑓(𝑡𝑖+1 , 𝑦𝑖 + ℎ𝑓(𝑡𝑖 , 𝑦𝑖 ))]
2
which is the Iterative formula for the Modified Euler’s method.

MATLAB MANUALS 118


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

15.2 MATLAB CODE


15.2.1 Task
Illustrate the implementation of Modified Euler’s method in MATLAB to find the solution of the given
first order Differential equation:

𝒅𝒚
= 𝟒𝒆𝟎.𝟖𝒙 − 𝟎. 𝟓𝒚
𝒅𝒙

With an Initial condition 𝒚(𝟎) = 𝟐 using 𝒉 = 𝟎. 𝟓 with the range of 𝒙 = 𝟎 to 𝒙 = 𝟏.

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

fprintf('Modified Euler Method: \n'); % for display text


fprintf(' i x(i) y(i+1) \n'); % for display of headings

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

fprintf('\n Solution of first order Differential Equation using Modified


Euler method is: %f\n',y(i+1));
Output
Modified Euler Method:
i x(i) y(i+1)
1 0.00000 3.7553055163
2 0.50000 6.2051138610
3 1.00000 9.7279236287

Solution of first order Differential Equation using Modified Euler method is: 9.727924

MATLAB MANUALS 119


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

15.3 RUNGE-KUTTA METHOD OF ORDER-4


ALGORITHM

Euler’s method is given by yi 1  yi  f xi , yi h where x0  0 , y0  y( x0 ) , h  xi 1  xi

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

 yi  f ( xi , yi )xi 1  xi   f ' ( xi , yi )xi 1  xi   f ' ' ( xi , yi )xi 1  xi   ...


1 2 1 3

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.

The true error in the approximation is given by

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 

k 2  f xi  p1h, yi  q11k1h

This form allows one to take advantage of the 2nd order method without having to calculate f x, y  .

MATLAB MANUALS 120


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

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.

15.4 MATLAB CODE


15.4.1 Task
Use the classical 4th order Runge-Kutta method to find the solution of the given first order
differential equation in MATLAB.

𝒅𝒚
= 𝟒𝒆𝟎.𝟖𝒙 − 𝟎. 𝟓𝒚
𝒅𝒙
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');

MATLAB MANUALS 121


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

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

fprintf('\nk1=%f \nk2=%f \nk3=%f \nk4=%f \n',k1,k2,k3,k4);


fprintf('\nSolution of First order Ordinary Differential
equation:%f\n',y(i+1));

% FOR EXACT SOLUTION


xspan=0:0.5:1; % range for x values
y(1)=2;
fprintf('\n Exact solution is: ');
[x,y]=ode45(f,xspan,y(1)) % Direct solution syntax
plot(x,y)
xlabel('x-axis');
ylabel('y-axis');
title('Exact solution');
grid on
axis tight
Output

Runge-Kutta method of order-4


i k1 k2 k3 k4 y(i+1)
1 3.00000 3.13561 3.10171 3.41644 3.57426
2 4.18017 4.45630 4.38727 4.92140 5.80665
3 5.99884 6.47009 6.35228 7.20100 9.04370
k1=5.998839
k2=6.470093
k3=6.352279
k4=7.201003
Solution of First order Ordinary Differential equation: 9.043699
Exact solution is:
x=
0
0.5000
1.0000
y=
2.0000
3.7515
6.1946

MATLAB MANUALS 122


SESSSION: 2016-2020 Chemical Engineering Department
2222222020

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

MATLAB MANUALS 123

You might also like