0% found this document useful (0 votes)
14 views

MATLAB 1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

MATLAB 1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Computer Applications in

Chemical Engineering
CHE 247

Dr. Rabya Aslam


Institute of Chemical Engineering and Technology
University of the Punjab, Lahore 54590 1
June 2022 [email protected]
Recommended Books
▪ Amos Gilat, MATLAB: An introduction with
applications, 5th edition, John Wiley and Sons, Ltd
▪ Bruce A. Finlayson (2006), “Introduction to
Chemical Engineering Computing”, John Wiley
and Sons, Ltd.

▪ N.W Loney (2001) “Applied Mathematical methods


for Chemical Engineers” CRC Press.

▪ Timothy A. Davis and K. S., (2004),”Matlab


Primer”, 7th Edition, CRC Press.

▪ Michael B. Cutlip, Problem Solving in Chemical


and Biochemical Engineering with POLYMATH™,
Excel, and MATLAB 2
Topic 1

Introduction

3
MATLAB Introduction

Matlab Windows

4
MATLAB Introduction

workspace
Command window

5
Working in the command window

✓ Main window to execute commands


✓ Cursor must be next to command prompt >>
✓ Type and press enter
✓ Several commands in one line, use , as
separator
✓ No corrections can be made to executed
command
✓ Already typed commands can be displayed
using uparrow
✓ Long command can be continued to next line
using … at the end of the line
✓ Max 4096 characters

6
MATLAB arithmetic operations with scalars

Operation Symbol Example


Addition + 2+4
Subtraction - 3-1
Multiplication * 3*4
Right division / 4/2
Left division \ 6\2=2/6
Exponentiation ^ 3^4 = 34

7
Selected display formats
Command Example Description
format short >>290/7 => 41.4286 Fixed point with 4 decimal digits

format long >>290/7 =>41.42857142857143 Fixed point with 15 decimal digits

format short e >>290/7 =>4.1429e+001 Scientific notation with 4 decimal digits

format long e >>290/7 Scientific notation with 15 decimal digits


=>4.142857142857143e+001

format short g >>290/7 =>41.429 fixed-decimal format or scientific notation,


whichever is more compact, with a total of
5 digits.
format long g >>290/7 =>41.4285714285714 fixed-decimal format or scientific notation,
>>4.000000 whichever is more compact, with a total of
15 digits for double values, and 7 digits
for single values
format bank 290/7 => 41.43

format compact Elimintes empty lines

format loose Adds empty lines 8


MATLAB commands and built-in functions
Try the followings on the command prompt:
>>clc >>sind(90)
>>clear >>sin(0.2)
>>doc log10 >>format long
>>help log10 >>format short
>>pi >>abs(-3)
>>inf >>sqrt(16)
>>eps >>exp(2)
>>log10(10) >>factorial(3)
>>log2(2) >>rem(5,4)
>>log(2.7183) >>acosd(1)
9
>>who >>whos
Rules about variables names
✓ Variable => made of single or many letters
✓ Each variable is assigned a value (This variable can then
be used in expressions, functions, statements, or
commands)
✓ A variable can be assigned a single value at one time
✓ Variable must begin with a letter
✓ A and a are different in matlab environment
✓ Avoid using names of built-in functions as names of
variables, this will produce errors on executions
✓ If variable is assigned a new value, old value is replaced
with the new value
✓ Avoid using the names of a built in function for a variable
(e.g. avoid using cos, sin, exp, sqrt, tan, mean etc.). Once a
function name is used to defined a variable, the function
cannot be used.

10
Topic 2

MATLAB as Calculator

11
Problem 1: Simple mathematical expression

Solve the followings and format answer to 4 decimal


points:

Semicolon (;) at the end of command will suppress


the output
12
Topic 3

Array operations in MATLAB


Vectors and Matrices

13
Creating Arrays in Matlab
▪ The array is a fundamental form that MATLAB uses
to store and manipulate data
▪ An ARRAY is a list of numbers arranged in ROWS
and COLUMNS
▪ ARRAYS are characterized by their DIMENSIONS.
▪ VECTOR is ONE dimensional ARRAY
▪ Matrix is a TWO dimensional ARRAY
▪ ARRAYS can have higher dimensions
▪ VECTORS are ROW or COLUMN vectors
▪ Data in the ARRAYS are NUMBERS or
CHARACTERS

14
Creating Arrays in Matlab
Enter a statement like following in matlab command window
and press entre

Arrays/ vectors are created within square


brackets [ ] in MATLAB. If you have random data,
add numbers within [ ]. Each data can be
separated by simply using space between two
numbers or simply using comma between two
numbers. 15
Creating Arrays in Matlab

16
Creating Arrays in Matlab

The linspace and logspace functions


The function linspace can be used to initialize a vector of equally spaced
values:

The function logspace can be used to generate logarithmically spaced data.


It is a logarithmic equivalent of linspace. To illustrate the application of
logspace try the following

17
Array operations
Equally spaced data can also be generated using
following command

X=[initial number:difference between two numbers: final number]

18
Array operations
• Array Addressing and Selecting Array Elements
a= [ 1 2 3 4]
a (3) 3rd element will be displayed
In Matlab, index arrays inside of parenthesis are used to
select elements of an array. The colon operator is used
to select an entire row or column.

19
Class Practice
Create one dimensional array within range of 1 to 100 with
step of
a. 1
b. 0.5
c. 2.5
d. 10

20
Built in functions
Generate data using linspace command within 0 to 10 and try following
built-in functions
1. mean(x)
2. max(x)
3. min(x)
4. sort(x)
5. median(x)
6. std(x)
7. rand
8. rand(2,2) rand(rows, columns)
9. rand(2,4)
10. rand(3)
11. randperm(5)
12. randperm(5,3)

21
Creating 2-dimensional array

a=[1 2 3 ; 4 5 6; 7 8 9];
a=[(1:1:3); linspace(4,5,3) ; 7 8 9];

22
Creating 2-dimensional array

a=[1 2 3 ; 4 5 6; 7 8 9]
a=[(1:1:3); linspace(4,5,3) ; 7 8 9]
a=zeros (rows, columns) (create zero vector of given
size of rows and columns)

a = ones (rows, columns) (create vector with every


element 1 of given size of rows and columns)

a= eye (rows, columns) (create I vector of given size of


rows and columns)

a=rand(m,n) (create mxn size vector of random numbers (from


0 to 1.)

a=randperm(n) creates a single row vector of n columns with


random numbers from 1 to n. 23
Array Operations in Matlab

b = [ 5 4 6; 7 8 9; 1 2 3]
b(:,:) both column and rows will be displayed
b(1,:) elements of 1st rows will be displayed
b(:,3) elements of 3rd column will be displayed

24
Array operations
b(:,[1 3]) elements of 1st and 3rd column will be displayed.
b(5) 5th element will be displayed
diag(b) elements of diagonal will be displayed
Demonstration using MATLAB

() are used to call any element

25
Changing and Deleting Array Elements
Elements can be changed by selecting a portion of an array as
the left-hand-side target of an assignment statement:
For example, if
a=[1 2 3 4 5]
a(2) may be replaced with 10 using following command
a(2) = 10

>> a=[1:1:5];
>> a(1,3)=0 Replace 3rd element of 1st row with zero
a=
1 2 0 4 5
>> a([1,3])=0
Replace 1st and 3rd element with zero
a=
0 2 0 4 5
26
Changing and Deleting Array Elements

To delete selected elements of a vector:


a(2) =[] Delete 2nd element from the vector

a(:,2) = [] Delete complete second column of the


matrix

a(1,:) = [] Delete complete 1st row of the matrix

Demonstration using MATLAB

27
Manipulating Arrays
Transpose
Transpose of A = A’
fliplr(A) (Flip left/right)
flipud(A) (Flip up/down)

[a,b] To link or combine two matrices


a(:) To link both rows and column of a matrix

Combine rows and column in to


single column matrix

Link two matrices

28
Some built in functions
• length(a)
• size(a)
• reshape(a,m,n)
• diag(v)
– More from help in Elementary Matrix and
Matrix Manipulation

29
Multiplication and addition
• Scalars A scalar can be added to or multiplied with each
element of an array; e.g.,
A = [1 3 4 5 7 8 ]
for 2 + A
ans will be ans= 3 5 6 7 9 10

Scalar is multiplied with each element of matrix

30
Multiplication and addition

31
Multiplication and addition
Arrays are multiplied together in two different ways:
▪ matrix multiplication, where the inner dimensions of the arrays
must be the same
▪ element-by-element multiplication, indicated by the use of a
dot (.) along with the operator, where the arrays must have
compatible sizes

32
Multiplication and addition

Use MATLAB array operations to do the following:


1. Add 1 to each element of the vector [2 3 -1].
2. Multiply each element of the vector [2 3 -1] by 5.
3. Find the array product of the two vectors [1 2 3] and [0 -1 1].
4. Square each element of the vector [2 3 1].
5. Divide each element of the vector [2 3 1] by 0.5.

33
Array division
▪ If AB=BA=I then
▪ B is inverse of A and A is inverse of B and I is an
identity matrix
▪ All A, B, and I are square matrices
Inverse of A = A^(-1) or inv(A)
▪ LEFT division \ : to solve matrix equation AX=B
In matlab X=A\B
or X = inv(A)*B
▪ In MatLab X= A\B
▪ RIGHT division “/” is used to solve XC=D where X and
D are ROW vectors
X= D/C
34
Array determinant

• Determinant is a function that associates a


number with a square matrix
• Determinant of a = det(a)

35
Linear Algebra Solution

Solve the set of linear equations


4x - 2y + 6z = 8
2x + 8y + 2z = 4
6x +10y + 3z = 2
Find the values of x,y and z.

4 −2 6 𝑥 8
2 8 2 𝑦= 4
6 10 3 𝑧 2

36
Summation
The elements of a single array can be added
together using the sum and cumsum functions
sum(a) Vector summation or each column of matric is summed up.

cumsum(a) Cumulative summation

sum(a,2) Summation along rows

sum(a,1) Summation along columns

Sum(sum(a)) Summation of entire matrix

37
Strings and string variables

▪ ‘abc’ is a string
▪ ‘a256cc’ or ‘matlab’ or ‘3%abc’ are all strings
▪ Used
▪ to display text messages
▪ In formatting commands of plots
▪ Input argument of some functions
▪ A=‘this is a string’
▪ A=‘the numbers are 50 out of 100’

38
Concept of simple script file

Commands can be saved in the form of program and can be called


anytime, in MATLAB command window, commands are executed
in same sequence as written.

39
Concept of simple script file
Find the vapor pressure of water using Antoine equation within
temperature range of 293 to 373 K.

Where A = 5.40221, B = 1838.675, C = -31.737


% P = vapor pressure (bar) and T = temperature (K)
disp('vapor pressure data of water')
A=5.40221;
B=1838.675;
C=-31.737;
T=[273:5:373];
P=10.^(A-(B./(T+C)));

40
Output: Disp and fprintf commands
The disp statement
The general form of disp for a numeric variable is
disp( variable )

disp command can be used to


display a message enclosed in
apostrophes (called a string).

You can display more than one


number on a line as follows: disp(
[x y z] )

The fprintf command


Format the output to required format. You may use this command to write
in a file as well or directly at command window.

Text printing in new line


41
Output command

Input and Output Commands


MATLAB provides the following input and output related commands −

Command Purpose
disp Displays contents of an array or string.
format Controls screen-display format.

fprintf Performs formatted writes to screen or file.

input Displays prompts and waits for input.


; Suppresses screen printing.

42
fprintf command

fprintf support the following format codes −

Format Code Purpose


%s Format as a string.
%d Format as an integer.
%f Format as a floating point value.

%e Format as a floating point value in scientific notation.

%g Format in the most compact form: %f or %e.


\n Insert a new line in the output string.
\t Insert a tab in the output string.

43
Class activity
Find the vapor pressure of water using Antoine equation within
temperature range of 293 to 373 K.

Where A = 5.40221, B = 1838.675, C = -31.737


% P = vapor pressure (bar) and T = temperature (K)
disp('vapor pressure data of water')
A=5.40221;
B=1838.675;
C=-31.737;
T=[273:5:373];
P=10.^(A-(B./(T+C)));
result=[T;P]
fprintf('%s\t %6s\n\n', 'T','P');
fprintf('%0.2f\t %0.2f\n', result)

44
fprintf to save output to a file

45
fprintf to save output to a file

46
Class Activity
1: Solve the set of linear equations
2x - 12y = 0
2x + 8y + 2z = 8 X=inv(A)*B
6x +10y + 3z = 1
Find the values of x,y and z.
2: generate an array x (0-2pi) and apply cos(x),
sin(x)
Note: command to convert degrees to radians in MATLAB is deg2rad(x)
or sind(x),cosd(x) or define x in form of pi.
3: generate an array and take mean, standard
deviation, summation, maximum, minimum and
median. Also sort the data in ascending and
descending order.
47
Vectors: summary

48
Vectors: summary

49
Matrices: summary

50
Matrices: summary

51
Plotting and concept of script files

52
2D Plotting

▪ Plot
▪ Axis labels
▪ Scale
▪ Titles
Elements of 2D plot
▪ Legend
▪ Text
▪ Line style
▪ Marker

53
2D Plotting: Elements of 2D plot
▪ Plot command is used to plot graph
between two variables x and y.
plot(x,y)

54
2D Plotting: Elements of 2D plot

Plot(variable-1,variable-2, 'line color and line


specifiers”)
For example
If
X=x=[0:pi/60:2*pi]
y=sin(x)
plot(x,y,'b-.')

55
2D Plotting: Elements of 2D plot
x=[0:5:360];
y=sind(x);
z=cosd(x);
plot(x,y,'k-')
hold on
title('trignometric functions in 4th semester class
CHE247')
xlabel('angle in degrees/(units)')
ylabel('sinx')
plot(x,y,'g-')

56
2D Plotting: Line specifiers

57
2D Plotting: Line color specifiers

Color specifier Color specifier

Red r Magenta m

Green g Yellow y

Blue b Black k

Cyan c White w

58
2D Plotting: Element of graph
title('title')
xlabel('xlabel')
ylabel('xlabel')
xlim([minimum value max-value])
ylim([minimum value max-value])
legend(‘string1’, 'string2’)
axis equal
axis square

59
2D Plotting: axis
xlim([minimum value max-value])
ylim([minimum value max-value])
axis equal
axis square
axis tight
axis normal

grid on
grid off

60
2D Plotting: Element of graph

Am easy way to write element of graph are using


figure editor, however during script writing always
better and handy to use commands

61
Plotting multiple graphs
plot (x,y,x,z)
or use the command of hold on and plot multiple
graphs on same figure

62
Class Activity

x=[0:5:360];
y=sind(x);
z=cosd(x);
plot(x,y,'--g','LineWidth',2,'MarkerSize',10,...
'MarkerEdgeColor','b')
xlabel('angle')
ylabel('sinx')
hold on
plot(x,z,'r','LineWidth',4,'MarkerSize',3,...
'MarkerEdgeColor','g')
legend('sinx','cosx')

63
Class Activity

x=linspace(0,1,100);

64
Semi log and log-log plots

• semilogy(x,y)
• semilogx(x,y)
• loglog(x,y)

• Caution
– Log of 0 does not exist
– Log of –ve number is complex

65
Try other common plots

• bar(x,y)
• barh(x,y)
• stairs(x,y)
• stem(x,y)
• pie(x)
• hist(x)

66
Class Practice

Generate an array x and apply cos(x), sin(x)


and plot graphs for x vs sin(x), x vs cos(x),
and x vs tan(x)
▪ Label the graphs properly.
▪ Plot all the graphs on same figure.
Use subplot(3,1) and plot these graphs at
various positions

Note: command to convert degrees to radians in MATLAB is deg2rad(x) or sind(x),cosd(x) or define x


in form of pi.
67
Class Activity
Find the vapor pressure of water using Antoine equation within
temperature range of 293 to 373 K.

Where A = 5.40221, B = 1838.675, C = -31.737


% P = vapor pressure (bar) and T = temperature (K)
disp('vapor pressure data of water')
A=5.40221;
B=1838.675;
C=-31.737;
T=[273:5:373];
P=10.^(A-(B./(T+C)));
plot(T,P,'r','LineWidth',2);
title('vapor pressure data');
xlabel('temperature/K');
ylabel('vapor pressure in bar');
result=[T;P]
fprintf('%s\t %6s\n\n', 'T','P'); 68
fprintf('%0.2f\t %0.2f\n', result)
Class Assignment
An ideal gas is one in which all collisions between molecules are perfectly elastic. It
is possible to think of the molecules in an ideal gas as perfectly hard billiard balls
that collide and bounce off of each other without losing kinetic energy. Such a gas
can be characterized by three quantities: absolute pressure (P), volume (V), and
absolute temperature (T). The relationship among these quantities in an ideal gas is
known as the ideal gas law:
PV=nRT
where P is the pressure of the gas in kilopascals (kPa), V is the volume of the gas in
liters (L), n is the number of molecules of the gas in units of moles (mol), R is the
universal gas constant (8.314 L-kPa/mol-K), and T is the absolute temperature in
kelvins (K). (1 mol 5 6.02 x1023 molecules)
Assume that a sample of an ideal gas contains 1 mole of molecules at a
temperature of 273 K, and answer the following questions.
(a) How does the volume of this gas vary as its pressure varies from 1 to 1000
kPa? Plot pressure versus volume for this gas on an appropriate set of axes.
(b) Suppose that the temperature of the gas is increased to 373 K. How does the
volume of this gas vary with pressure now? Plot pressure versus volume for
this gas on the same set of axes as for part (a).

69
Subplot (m,n,p)

Subplot (m,n,p)
(2,3,1) (2,3,2) (2,3,3)

(2,3,4) (2,3,5) (2,3,6)

Subplot(2,3,1), plot(x,y)
Subplot(2,3,2), plot(x,y)
70
Demonstration in the class
Lab Assignment-WFT-1a

One of the most successful correlations is called Antoine equation, which


uses three coefficients, A, B, and C, which depend on the substance being
analyzed. Antoine equation is as follows:

a. Write a script file to plot the vapor pressure of following components in


MATLAB in kPa vs temperature in K within temperature range of 273 K to
373 K for the following substances
1. Benzene
2. Water
3. Ethanol
b. Plot all graphs on same page using subplot command via script file

71
Lab Assignment-WFT-1b

a) Using script file option and fprintf command


1: write a program to prepare a conversion table
for cm to inches. Values in cm are 1-10 with step
size of 1 cm. Print the results in file via fprintf
command upto 3 decimal points

b) Write a script file to plot sinx, cosx within 0-pi.


Write all commands in script file to format the
charts. Print the results of x, sin x and cos x using
fprintf command up to 3 decimal points.

72
Explore 3D-plotting
Commands used for 3D plotting are
1. plot3(x,y,z)
2. surf(x,y,z)

73
3D-plot

plot3(x,y,z)

74
Polynomial equation

75
Polynomial equation

Note: By convention, MATLAB® returns the roots in a


column vector.

76
Polynomial equation

77
Polynomial equation-summary

78
Lab practice

4: find the roots of following polynomial


equations

[1 9 28 38 24]

79
Pressure of a gas using a cubic equation

80
Solution
clear, clc
%Pressure of toluene gas using van der Waals equation of state
n=0.25; %kmol
V=0.55; %m3
T=350; %oC
T=T+273.15; %K
Tc=591.75; %K
pc=4108; %kPa
R=8.3145; %m3.kPa/(kmol.K)
a=(27/64)*(R^2)*(Tc^2)/pc; %m6.kPa/kmol2
b=(R*Tc)/(8*pc); %m3/kmol
v=V/n; %m3/kmol
p=((R*T)/(v-b))-(a/(v^2)) %kPa

What about p using ideal gas law?


Calculate and compare both values.
81
Pressure of toluene gas :practice
clear, clc
%Pressure of toluene gas using van der Waals
equation of state
n=input('The value of n is: '); %kmol
V=0.55; %m3
T=350; %oC
T=T+273.15; %K
Tc=591.75; %K
pc=4108; %kPa
R=8.3145; %m3.kPa/(kmol.K)
a=(27/64)*(R^2)*(Tc^2)/pc; %m6.kPa/kmol2
b=(R*Tc)/(8*pc); %m3/kmol
v=V/n; %m3/kmol
p=((R*T)/(v-b))-(a/(v^2)); %kPa
disp(p) 82
Function files, inline function, and global command

Function with name f1 (M-file with name f1), f1 function is


stored so that it can be called at any time:
function y=f1(x) On the command window
y=x^2+3*x+2; >> feval('f1',2)

Inline function f2. No need to write a separate M-file. It can


be written within a script or even on the command prompt.
It is then stored and it can be called at anytime:
>> f2=inline('x^2 +3*x +8','x') or
>>f2=@(x) x^2+3*x+8

83
fzero, fsolve, and roots built-in functions

function y=f1(x)
y=x^2+3*x+2;

Solving single algebraic equation with initial guess of 2.0:


>>x=fzero(f1, 2) or >>x=fzero(f1, 2)
>> feval(f2,2)

fsolve can be used to solve for the zero of a single variable


equation. However, fzero will find the zero if and only if the function
84
crosses the x-axis.
Density of CO2 using a cubic equation of state

Calculate the molar volume and density of CO2 at 50 bar


and 450 K (176.85°C) using ideal gas law and the Redlich-
Kwong (RK) equation of state. Under these conditions, the
molar volume given in Perry’s Handbook is 0.7065 m3/kmol
(p. 2-241, 8th ed.).
Cubic form of the Redlich-Kwong equation:

pc = 7374; %kPa 85
Tc = 304.12; %K
Density of CO2 using a cubic equation of state
%Density of CO2 using RK EoS
p = 5000; %kPa
T = 450; %K
R = 8.3145; %kPa.m3/(kmol.K)
pc = 7374; %kPa
Tc = 304.12; %K
M = 44.01; %kg/kmol
v_ig = (R*T)/p; %m3/kmol
den_ig = (p*M)/(R*T) %kg/m3
a = 0.42747*(R^2)*(Tc^2)/pc; %m6.kPa/lmol2
b = 0.08664*R*Tc/pc; %m3/kmol
alpha = sqrt(Tc/T);
fV_RK= @(v) v^3-(R*T/p)*(v^2)+((a*alpha/p)-(b*R*T/p)-(b^2))*v-(a*alpha*b/p);
v = fzero(fV_RK,v_ig); %m3/kmol
den = M/v

86
Solution using roots
clear, clc
%Problem 6: Density of CO2 using RK EoS
p = 5000; %kPa
T = 450; %K
R = 8.3145; %kPa.m3/(kmol.K)
pc = 7374; %kPa
Tc = 304.12; %K
M = 44.01; %kg/kmol
v_ig = (R*T)/p; %m3/kmol
den_ig = (p*M)/(R*T) %kg/m3
a = 0.42747*(R^2)*(Tc^2)/pc; %m6.kPa/lmol2
b = 0.08664*R*Tc/pc; %m3/kmol
alpha = sqrt(Tc/T);
Pe = [1, -(R*T/p), ((a*alpha/p)-(b*R*T/p)-(b^2)), -(a*alpha*b/p)];
v=roots(Pe); %m3/kmol
v=max(v)
den = M/v %kg/m3

87
Assignment-FTW2

Calculate the molar volume and density of N2 at 200 Psia


and 350 K using Soave-Redlich-Kwong (SRK) equation and
the Peng-Robinson equation. Solve the problem using fzero,
fsolve, and roots built-in MATLAB functions. Compare the
results with ideal gas law. pc = 492.45 psia
Tc = 126.2 K, MW =28 g/gmol
Cubic form of the Peng-Robinson equation:

Cubic form of the Soave- Redlich-Kwong equation:

88
Home Practice: inv, linsolve, and fsolve built-in
functions

89
Basic Statics and curve
fitting

90

You might also like