Vous êtes sur la page 1sur 81

Computer Applications in

Chemical Engineering

Dr. Rabya Aslam


Institute of Chemical Engineering and Technology
University of the Punjab, Lahore 54590 1
June 2019 rabya.icet@pu.edu.pk
Course contents
 Use of Excel for problem solving, plotting, fitting data, building
new functions, Ordinary differential equations, non linear
regression
 Matlab : Introduction to Matlab, Linear algebra applications:
matrix calculations, solution of linear equations, Plotting of
various types of graphs. Symbolic mathematics: symbolic
differentiation and solution of differential equations. Numerical
solution/calculation of integrals, derivatives and differential
equations. Numerical Methods: Review of Numerical methods
involving computers to solve ordinary differential equations,
partial differential equations, matrices and its application,
Solution of partial differential equations using Finite Difference
Method. Numerical Solution of Heat Equations, Laplace
Equations.
 Aspen Plus: Hands on experience to use Aspen plus and Aspen 2
Hysys for drawings and simulations.
Recommended Books
 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.

 Nayef Ghasem, “Computer Methods in


Chemical Engineering” CRC Press.

 Abdelwahab Kharab, Ronald B. G., (2001),


“An introduction to Numerical Methods, A
MATLAB approach”, CRC Press.

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


Primer”, 7th Edition, CRC Press. 3
4
Introduction to MATLAB

The name MATLAB stands for matrix laboratory. MATLAB was originally written
to provide easy access to matrix software developed by the LINPACK and EISPACK
projects, which together represent the state-of-the-art in software for matrix
computation.

MATLAB is a high-performance language for technical computing, developed by


Cleve Moler (an American mathematician and computer programmer specialized in
numerical analysis in the mid to late 1970s). MATLAB integrates computation,
visualization, and programming in an easy-to-use environment where problems and
solutions are expressed in familiar mathematical notation.
Typical uses include:
 Math and computation
 Algorithm development
 Modeling and simulation
 Data analysis, exploration, and visualization
 Scientific and engineering graphics
 Application development, including GUI building Cleve Moler

5
Getting started with MATLAB

Starting MATLAB:
On Windows platforms, start MATLAB by double-clicking the MATLAB shortcut icon
on your Windows desktop

MATLAB Desktop:

6
MATLAB Windows

 Command windows
 Figure window
 Editor window
 Help window
 Current directory
 Work space
 Command history

7
Getting started with MATLAB

8
Getting started with MATLAB

Quitting/ Exiting Matlab:

To exit, write exit in the command window and press enter

9
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

10
The semicolon (;)

 It suppresses the output in the command


window if typed at the end of the
commands
 Command;

11
The %, clc, clear, clf commands

 % at the beginning of a command turns it


to a comment only.
 clc command is used to clears the
command window, however, it does not
clear the user's history of commands
 clear command removes all the variables
from the current workspace, releasing
them from system memory.
 clf deletes the graphic objects from the
current figure.
12
Arithmetic Operations with scalars

Operation Symbol Example


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

13
Order of Precedence

Precedence Operation

1st ()

2nd ^

3rd * And /

4th + and -

14
Class practice: MATLAB as Calculator

Demonstration using MATLAB

15
Display formats

Command Example
format short >>290/7 => 41.4286
format long >>290/7 =>41.42857142857143
format short e >>290/7 =>4.1429e+001
format long e >>290/7
=>4.142857142857143e+001
format short g >>290/7 =>41.429
format long g >>290/7 =>41.4285714285714
format bank 290/7 => 41.43
format compact Elimintes empty lines
format loose Adds empty lines

16
Built in math functions

Function Description
sqrt(x) Square root
exp(x) Exponential
abs(x) Absolute value
log(x) Natural lorithim
log10(x) Base 10 logrithim
factorial(x) Factorial function x!

17
Built in trigonometric functions

Function Description

sin(x) Sine of angle x

cos(x) Cosine of angle x

tan(x) Tangent of angle x

cot(x) Cotangent of angle x

Note: command to convert degrees to radians in MATLAB is deg2rad(x)

18
Built in rounding functions

Function Description
round(x) Round to nearest integer
fix(x) Round towards zero
ceil(x) Round towards infinity
floor(x) Round towards –infinity
rem(x,y) Returns remainder of x is divided by
y
sign(x) Sign function, returns 1 if x>0, -1 if
x<0, and 0 if x=0

19
Pre defined variables

Variable Description
ans Name assigned to the last unassigned value by
matlab
pi The number Pi
eps The smallest difference between two numbers,
equal to 2^(-52)
inf Used for infinity
i Defined as (-1)^0.5
j Same as i
NaN Not a number, when matlab can not determine a
number value it assigns NaN to the variable, 0/0

20
Some useful commands

Command Outcome

clear Removes all variables from memory


(only workspace)
clear x y z Removes only x y z variables from
memory
who Displays list of variables in memory

whos Displays the list of variables along with


information of variables

21
Some useful points to remember

 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
 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
 Variable name and value appears in workspace and
command window
 If (;) is typed after the assignment statement, nothing
appears in the command window
 If variable is assigned a new value, old value is replaced
with the new value

22
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

23
Creating Arrays in Matlab

Creating One-Dimensional Array

1. Variable_name = [type vector elements]


2. Variable_name = [1 2 3] or [1,2,3]
3. Variable_name = [1;2;3]
4. Variable_name = [start number:space:last number]
5. Variable_name = linspace(1st number, last number, no.
of divisions)

24
Class practice to create one dimensional array

Demonstration using MATLAB

25
Lab practice and assignment
 Install MATLAB at your laptops, computers
 Familiarize yourself with matlab interface

A: Solve the following questions and report answers with


short and long format

1: 2+3*9/6 = ?
2: 23-6/7+8.3 = ?
1 1 1
3: + −
(2−0.1)2 +0.3 (6−0.5)2 +0.6 (8−0.1)2 −10.3

B: Create one dimensional array within range of 1 to 100


with step of
a. 1
b. 0.5
c. 2.5
d. 10 26
array operations

27
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)
a = ones (rows, 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.

28
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.
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(:,2) elements of second column will be displayed

29
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


30
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];
Replace 3rd element of 1st row with zero
>> a(1,3)=0
a=
1 2 0 4 5
>> a([1,3])=0 Replace 1st and 3rd element with zero
a=
0 2 0 4 5
31
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

32
Manipulating Arrays

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

To link or combine two matrices


[a,b] Number of rows of both matrices should be same
a(:) Convert matrix to a column vector

33
Some built in functions

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

34
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

35
Multiplication and addition

36
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

37
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
38
Array determinant

• Determinant is a function that associates a


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

39
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

40
Strings and string variables

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

41
Built in functions

C = mean(x) sum(x) std(x)

C = max(x) median(x) inv(x)

C = min(x) median(x) det(x)

sort(x) sort(x,’ descend’) cumsum(x)


(by default it sort
the data in
ascending order)

42
Lab practice

1: 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.
2: generate an array x 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.

43
Polynomial equation
Polynomial equation is represented by single row vector where
coefficients are written in descending order.

𝑝 = 3𝑥 3 + 𝑥 2 + 𝑥 + 4
In Matlab it will be written as

p=[3 1 1 4]

Roots can be found as


roots(p)

By convention, MATLAB® returns the roots in a column vector.

Poly(r) converts the roots to polynomial equation


poly([r1,r2])

44
Lab practice

4: find the roots of following polynomial


equations

45
2D and 3D Plotting

46
2D Plotting

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

47
2D Plotting: Elements of 2D plot

 Plot command is used to plot graph


between two variables x and y.
plot(x,y)

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

49
2D Plotting: Line specifiers

50
2D Plotting: Line color specifiers

Color specifier Color specifier

Red r Magenta m

Green g Yellow y

Blue b Black k

Cyan b White w
51
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

52
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

53
2D Plotting: Element of graph

Second and easy way to write element of graph are


using figure editor 

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

55
Class Activity

x=linspace(0,1,100);

56
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

57
Other common plots
• bar(x,y)
• barh(x,y)
• stairs(x,y)
• stem(x,y)
• pie(x)
• hist(x)

58
Polar plots
polar(theta,r)
Example
theta=linspace(0,2*pi,100)
r=3*sin(0.5*theta).^2+theta
polar(theta,r,'-r')

59
Lab Assignment
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. Plot the vapor pressure of following components in MATLAB in mbar vs


temperature in K within temperature range of 273 K to 373 K for the
following substances
You may find A,B,C
1. Benzene from Carl L. Yaws
2. Water handbook or
3. Ethanol Himmelblaue’s book
4. Methanol
5. Toluene
b. Plot T vs P curve for all components(part a.) on
single graph, use legends properly and properly
60
format the graph.
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)

Demonstration in the class


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

62
3D-plot
plot3(x,y,z)

63
Surface plot(3-D plot)

You may explore other 3D plot commands


from MATLAB help. Some examples are
3D vector plot
Streamline
Contour plot, etc.

64
Lab Assignment
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. Plot the vapor pressure of following components in MATLAB in mbar vs


temperature in K within temperature range of 273 K to 373 K for the
following substances
You may find A,B,C
1. Benzene from Carl L. Yaws
2. Water handbook or
3. Ethanol Himmelblaue’s book
4. Methanol
5. Toluene
. Plot all graphs on same page using subplot command

b
65
Scripts and Function Files

66
Scripts File
 Script file is a sequence of Matlab commands
 On RUN, commands executed one-by-one in the
order
 Outputs are displayed in command window if ; is
not used at the end of the commands
 Script files can be typed and edited in any editor
and then pasted in matlab editor
 Contain .m extension and also called m-files or
programs

67
Scripts File
 There are two different kinds of m-files. The simplest, a script file, is
a collection of MATLAB commands. When the script file is executed
by typing its name at the interactive prompt, MATLAB reads and
executes the commands within the m-file just as if these were
entering them manually. Executing a m-file is like cutting and
pasting the m-file contents into the MATLAB command window.

 The second kind of m-file contains a single function that has


the same name as that of the m-file. This m-file contains an
independent section of code with a clearly defined input/output
interface.

68
Writing and running m-file
 Click the New Script button on the Home tab.
 Use the edit function.
 Create the file and write the sequence of commands
 Save the file
 And execute by typing the name of file in command window
% example
disp(‘example’)
x = 0:.1:1;
A = [x; exp(x)];
plot(x,exp(x))
Demonstration with MATLAB

69
Writing and running m-file
Script M-files are ideal for repeating a calculation,
but with some parameters changed.

Demonstration with MATLAB

70
Output commands
• disp
– disp(name of a variable)
– disp(‘text as string’)

• fprintf (command used to print information on screen)


A formatting operator starts with a percent sign, %, and ends with a
conversion character. The conversion character is required. Optionally,
you can specify identifier, flags, field width, precision, and subtype
operators between % and the conversion character.

71
fprintf command

Character Description
e 1.709098e+002
E 1.709098E+002
f Fixed point notation
g Shorter of e or f notation
G Shorter of E or f notation
i Integer

72
fprintf command
value Type Conversion Details
Integer, signed %d or %i Base 10
Integer, unsigned %u Base 10
%o Base 8 (octal)
%x Base 16 (hexadecimal), lowercase letters a–f
%X Same as %x, uppercase letters A–F
Floating-point %f Fixed-point notation (Use a precision operator to
number specify the number of digits after the decimal point.)
%e Exponential notation, such as 3.141593e+00 (Use a
precision operator to specify the number of digits after
the decimal point.)
%E Same as %e, but uppercase, such
as 3.141593E+00 (Use a precision operator to specify
the number of digits after the decimal point.)
%g The more compact of %e or %f, with no trailing zeros
(Use a precision operator to specify the number of
significant digits.)
%G The more compact of %E or %f, with no trailing zeros
(Use a precision operator to specify the number of
significant digits.)
Characters or %c Single character
strings %s Character vector or string array. 73
Fprintf command

74
fprintf to save output to a file
 Open a file using fopen command
 Write the out put to open file using fprintf command
 Close the open file using fclose command
 Example is as follows

75
fprintf to save output to a file

76
fprintf to save output to a file

77
fprintf to save output to a file: example

78
Lab Practice and Assignment
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.

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 in text file as well.

79
Function files

Input data Output data


Function File

80
Function files

81

Vous aimerez peut-être aussi