CHEN309 Lec2

You might also like

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

CHEN 309: COMPUTER APPLICATIONS FOR CHEMICAL

ENGINEERS

INTRODUCTION TO GNU OCTAVE

April 2021
Learning Outcomes

At the completion of this module, the student


should be able to:
➢ Understand the GNU Octave workspace.
➢ Perform basic operations.
➢ Use common mathematical functions.
➢ Create and manage script M-files.
➢ Perform array operations.
➢ Control flow
What is GNU Octave?
GNU Octave is a high-level language primarily intended for
numerical computations. It is designed to be very easy for:
➔ Computations with vectors, matrices, etc…
➔ Standard but non-trivial mathematical operations
(e.g. polynomial root finding, matrix eigenvalue extraction,
statistical analysis, …)
➔ Plotting and customise plots
➔ It is not the kind of programming language used by
professional software engineers but it is good to learn
programming
➔ Octave is free software. It can be downloaded at
https://www.octave.org/download.html
Running Octave
 Command Line Interface (CLI)

 Graphical User Interface (GUI)

 On most systems, Octave is started with the shell command ‘octave’. This
starts the graphical user interface. The central window in the GUI is the
Octave command-line interface.

 If you get into trouble, you can usually interrupt Octave by typing Control-
C (written C-c for short).

 To exit Octave, type quit or exit at the Octave prompt.


GNU Octave Desktop
Getting help
 The entire text of GNU Octave manual is available from the Octave prompt via the command doc
>> doc
 The Documentation window contains
 Contents: Octave manual
 Function Index: List of built-in functions
 Search: To search through the documentation using
keywords
 The documentation for individual user-written functions and variables is also available via the help
command
>> help
>> help --list
>> help name
 Check what the keywords rand and size do.
Data Types
Logical
Class Syntax Description Examples
Name
logical logical(X) Convert the numeric object X to logical type. data = [ 1, 2; 3, 4 ];
idx = (data <= 2);
Any nonzero values will be converted to true (1) while data(idx)
zero values will be converted to false (0). ⇒ ans = [ 1; 2 ]

The non-numeric value NaN cannot be converted and


will produce an error.

Compatibility Note: Octave accepts complex values as


input, whereas MATLAB issues an error.

Logical/conditional operations
String
Class Syntax Description Examples
Name
char char (X) Create a string array char ([97, 98, 99], "",
char (X, ...) from one or more {"98", "99", 100}, "str1",
char (S1, S2, ...) numeric matrices, ["ha", "lf"])
char (CELL_ARRAY) character matrices, or ⇒ ["abc "
cell arrays. " "
"98 "
"99 "
"d "
"str1"
"half"]
Numeric integers
Class Name Syntax Description Examples

int*, uint* int*(X) Converts the >> float = rand (2, 2)


(*=8,16,32 elements of the array ⇒ float =
or 64) uint*(X) X into a signed or
unsigned *-bit 0.37569 0.92982
integers. X can be 0.11962 0.50876
any numeric object.
>> integer = int32 (float)

⇒ integer = 0 1 0 1
Floating point numbers
Class Syntax Description Examples
Name
single single(X) Convert X to single sngl = single (rand (2, 2))
precision type ⇒ sngl =
0.37569 0.92982
Most of the functions in 0.11962 0.50876
Octave accept single class (sngl)
precision values and ⇒ single
return single precision
answers.
double double(X) Convert X to double
precision type.

Default numeric type in


Octave.
Ranges of numeric data types
Data Type Min Max

Syntax Value Syntax Value

single realmin(‘single’) 1.1755e-38 realmax(‘single’) 3.4028e+38

double realmin(‘double’) 2.2251e-308 realmax(‘double’) 1.7977e+308

int8 intmin(‘int8’) -128 intmax(‘int8’) 127

int16 intmin(‘int16’) -32768 intmax(‘int16’) 32767

int32 intmin(‘int32’) -2147483648 intmax(‘int32’) 2147483647

int64 intmin(‘int64’) -9223372036854775808 intmax(‘int64’) 9223372036854775807

uint8 intmin(‘uint8’) 0 intmax(‘uint8’) 255

uint16 intmin(‘uint16’) 0 intmax(‘uint16’) 65535

uint32 intmin(‘uint32’) 0 intmax(‘uint32’) 4294967295

uint64 intmin(‘uint64’) 0 intmax(‘uint64’) 18446744073709551615


cell
Class Syntax Description Examples
Name
cell cell (N) It can be both necessary and myCell = {1, 2, 3;
cell (M, N) convenient to store several variables 'text', rand(1,2), {11;
of different size or type in one
cell (M, N, K, ...) variable. A cell array is a container
class able to do just that.
22; 33}}
cell ([M N ...]) In general cell arrays work just like N-
dimensional arrays with the exception
of the use of ‘{’ and ‘}’ as allocation
and indexing operators.
Cell Arrays
 A cell is a data type for unstructured information. In a cell
array, each element can have any data type, including
another cell. However, elements of cell arrays are indexed
using braces, {}, rather than parentheses. They are also
concatenated using braces. Alternatively, you can create a
cell array using the cell function, then populate the elements
one by one.

 Example: Create a 1×3 cell array where the first element is


the string ‘B22’, the second element is the double 43, and the
third element is a cell consisting of the four elements: ‘1st’,
‘2nd’, 4+2i and [2 4 5].
Struct arrays
 A struct is a data type that is useful when each element of an
array is defined by several properties.
 Syntax
 S= struct ()
 S=struct(FIELD1, VALUE1,FIELD2, VALUE2, ...)
 S = struct (OBJ)
 Example: Let a student be defined by a name (char), personal
ID number (char), and an array of grades (double). Populate a
struct array student with field names, ID, and grades. Verify
that student has type struct using the class function.
Variables
➔ A variable is a memory location whose value may
be changed during execution of a program.
➔ Programs work by changing the contents of memory,

so computer programs work by changing the values


of variables.
Variables
➔ Variable name must begin with a letter.
➔ It can contain letters (a-z, A-Z), numbers (0-9), and the
underscore ( _ ).
➔ Punctuations, spaces and special characters (except the
underscore) are not allowed.
➔ Variable name is case sensitive (Date and date represent two
different variables).
➔ The length of the variable is unlimited, but only the first N
characters are significant. To find N use the command
>> namelengthmax
Reserved Variables with Special Meanings

NOTE: Never redefine the meaning of a predefined variable in Octave


Basic Arithmetic Operations
MATRIX OPERATIONS ARRAY OPERATIONS

Operation GNU Octave Precedence Element-wise multiplication


Symbol
.*
./ Element-wise division
Parenthesis () 1
Exponentiation ^ (or **) 2 .^ Element-wise exponentiation
Multiplication * 3
Division / and \ 3
Addition + 4
Subtraction - 4
Expression and Assignment
 An expression is a combination of values, variables, and operators.
 Examples: >> 3*x + sqrt((x^3+5)/(x-10))
>> 4*y <= 3*y^2

 An assignment statement creates new variables and gives them values.


 Examples: >> x = 10

>> y = 2*x – 5
>> y = y + 1

 Note that the symbol “=” , called assignment operator, is different from the
usual algebraic equality sign.
Examples of Basic Arithmetic Operations
Mathematical expression/equation Octave expression/equation

−𝑏+ 𝑏 2 −4𝑎𝑐 x = (-b + sqrt(b^2 – 4*a*c))/(2*a)


x= 2𝑎 x = (-b + (b^2 – 4*a*c)^0.5)/2/a
𝑎
𝑃+ 𝑉 − 𝑏 − 𝑅𝑇
𝑉2 (P + a/V^2)*(V-b)-R*T
1
R= 1 1 1
+ +
𝑟1 𝑟2 𝑟3
R=1/(1/r1+1/r2+1/r3)
4
𝑎+ 𝑏 (a+b^(1/4))/(2/(a^2+5))-1
−1
2
𝑎2 + 5
2𝑛−1 − 1 t_half = (2^(n-1)-1)/((n-1)*Co^(n-1))
𝑡1 =
2 (𝑛 − 1)𝐶0𝑛−1
Matrix and Array Operations
 In Octave, double arrays are created using square brackets [ ].
 It is common to separate columns by commas (or space) and rows by semicolons (or Enter
key) within a concatenation.
 You can create an empty array by placing brackets around nothing.
 Things to cover
 Creating vectors and matrices
 Use of transpose
 Special Matrices (e.g. ones, zeros, eye, magic, rand etc)
 Slicing matrices
 Matrix and array operations
 Functions such as det, inv, eig etc
 Solving system of equations using \
Common Mathematical Functions
Common Mathematical Functions
Common Mathematical Functions
Common Mathematical Functions
Class Exercise
 For each of the following, state whether it is a valid or an invalid
Octave variable name?
(1) myName (2) finalConcentration% (3) 2ndVar
(4) Total Pressure (5) studentGPA (6) Initial_Velocity
(7) rxn+rate (8) studentRegistrationNumber
 Write the Octave equivalent of the following equations
𝑟−ℎ
V = 𝑟 2 𝑐𝑜𝑠 −1 − 𝑟−ℎ 2𝑟ℎ − ℎ2 𝐿
𝑟
1/𝑛
∆𝑃 𝑛 1+𝑛 /𝑛 1+𝑛 /𝑛
𝑣𝑧 = 𝑅 −𝑟
2𝐾𝐿 1+𝑛
Relational Operators
 Comparison operators are:
Operator Meaning

< Less than


> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
~= Not equal to

 The comparison (relational) operators return 1 for true and 0 for false.
 Note the following built-in functions: lt(a,b), gt(a,b), le(a,b), ge(a,b), eq(a,b),
ne(a,b)
Logical Operators
 Logical operators are:
Operator Meaning
& AND
| OR
~ NOT

 Logical operators are used to build compound relational


expressions which return 1 for true and 0 for false
 Note the build-in functions: and(x,y), or(x,y), xor(x,y),
not(x)
Truth Table

X Y X AND Y X OR Y X XOR Y

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0
Plotting
 2-D Line Plots
 Linear : plot(xvect,yvect)
 Logarithmic Plot: loglog(xvect,yvect)
 SemiLogarithmic Plots: semilogx(xvect,yvect)
semilogy(xvect,yvect)
 Plots with special graphics
 Vertical bar plot: bar(xvect,yvect)
 Horizontal bar plot: barh(xvect,yvect)
 Stairs plot: stairs(xvect,yvect)
 Stem plot: stem(xvect,yvect)
 Pie chart: pie(x)
 Histogram: hist(y)
 Scatter: scatter(xvect, yvect)
Plotting
 3-D Plots
 3-D line plot plot3(X,Y,Z)
 Creating grid points meshgrid(X,Y)
 Mesh plot mesh(X,Y,Z)
 Surface plot surf(X,Y,Z)
 Contour plot Contour(X,Y,Z)
 Surface + Contour plot surfc(X,Y,Z)
Plotting
For example, try
>> x = 0:1:100;
>> y = 2.*x.^2;
>> subplot(2,2,1); plot(x,y);
>> subplot(2,2,2); loglog(x,y);
>> subplot(2,2,3); semilogx(x,y);
>> subplot(2,2,4); semilogy(x,y)
Plotting
For example, try
>> t = linspace(0,10*pi);
>> plot3(sin(t),cos(t),t);
>> xlabel(‘sin(t)’);ylabel(‘cos(t)’);zlabel(‘t’)

Also try
>>[X,Y] = meshgrid(-2:0.1:2, -2:0.1:2);
>> Z = X.ˆ2 - Y.ˆ2;
>> figure (1); mesh(X,Y,Z);
>> figure (2); contour(X,Y,Z);
>> figure (3); surf(X,Y,Z);
>> figure (4); surfc(X,Y,Z)
Plotting
 Axis labels and a title can be added using the commands:
>> title(‘Simple Plot’);
>> xlabel(‘x’);
>> ylabel(‘Sine and Cosine’);
 Octave tries to choose sensible extreme values for the axes.
These can be overwritten using the command axis(v) where
v=[Xmin Xmax Ymin Ymax]
 Most plot properties can be edited from the plot window by
clicking on the little diagonal arrow on the tool bar then clicking
on any feature of the plot you’d like to edit (axis, curve thickness
color…)
Plot
Example: Sombrero plot
tx = ty = linspace (-8, 8, 41)';
[xx, yy] = meshgrid (tx, ty);
r = sqrt (xx .^ 2 + yy .^ 2) + eps; tz = sin (r) ./ r;
mesh (tx, ty, tz);
xlabel ("tx"); ylabel ("ty"); zlabel ("tz");
title ("3-D Sombrero plot");
Display Formatting Commands
Style Result Example
short (default) Short, fixed-decimal format with 4 digits after the decimal point. 3.1416
long Long, fixed-decimal format with 16 significant figures 3.141592653589793
shorte or shortE Short scientific notation with 4 digits after the decimal point. 3.1416e+00 or 3.1416E+00

longe or longE Long scientific notation with 15 digits after the decimal point 3.141592653589793e+00
for double values, and 7 digits after the decimal point for single values. 3.141592653589793E+00
shortG short or shortE, whichever is more compact. 3.1416
longG long or longE, whichever is more compact. 3.14159265358979
shortEng Short engineering notation (exponent is a multiple of 3) with 4 digits 3.1416e+000
after the decimal point.
longEng Long engineering notation (exponent is a multiple of 3) with 15 3.14159265358979e+000
significant digits.
+ Positive/Negative format with +, -, and blank characters displayed for +
positive, negative, and zero elements.
bank Currency format with 2 digits after the decimal point. 3.14
hex Hexadecimal representation of a binary double-precision number. 400921fb54442d18
rat Ratio of small integers. 355/113
bit Print the bit representation of numbers as stored in memory. Always print 010000000000100100100001111
the most significant bits first. 110110101010001000100001011
0100011000
Example: Energy stored in a spring
The force required to compress a linear spring is given by the equation
𝐹 = 𝑘𝑥
Where F is force in N and k is the spring constant in N/m. The potential energy E (in J)
stored in the compressed spring is given by the equation
1
𝐸 = 𝑘𝑥 2
2
The following information is available for four springs

Spring 1 Spring 2 Spring 3 Spring 4


Force (N) 20 24 22 20
Spring constant k (N/m) 500 600 700 800
Determine the compression of each spring and the potential energy stored in each
spring. Which spring has the most energy stored in it.
Example 1: Stirlings approximation
Stirling approximation is given as
𝑁
𝑁
𝑁! ≈ 2𝜋𝑁
𝑒
Use Octave to:
a. evaluate N! directly using the built-in function (factorial)
for N = 1 to 20
b. evaluate N! using Stirling’s approximation for N = 1 to
20
c. calculate the absolute and relative errors of the
approximated values.
Example 1: Stirling’s approximation
clear all % absolute error
clc abs_err = abs(S_Approx-N_fact);
% Create an array N
N = [1:20]’; % relative error
rel_err = abs_err./S_Approx;
% Evaluate the factorial using Octave built-
in function % print out values
N_fact = factorial(N); format shortg
res =[N N_fact S_Approx abs_err rel_err]
% Evaluate the factorial using Stirling disp(' N , N_fact, S_Approx, abs-err, rel_err’)
approximation
disp(res)
S_Approx =sqrt(2*pi*N).*((N/exp(1)).^N);
Script and Function Files

M-Files

Script Function
files files
Script File
 A script file is a list of Octave commands, called a program, that is saved in a
file.

 When the script file is executed (run), Octave executes the commands.

 3 ways to assign value to a variable


 The variable is defined and assigned a value in the script file
 The variable is defined and assigned a value in the Command Window
 The variable is defined in the script file, but a specific value is entered in the
Command Window when the script file is executed.
variable_name = input(‘string with a message that
is displayed in the Command Window’)
Function File
 Function file

 Syntax

 The word “function,” typed in lowercase letters, must be the


first word in the function definition line.
Useful Functions with M-Files
Command Comment
disp(ans) Display results without variable names
echo Control the Command Window echoing of script file commands
input Prompt user for input
pause Pause until user presses any keyboard key
pause(n) Pause for n seconds
% (or #) Comment line
fprintf Write data to text file
fopen(fid) Open the file specified by the file descriptor fid.
fclose(fid) Close the file specified by the file descriptor fid.
save The save command allow data to be written to disk files in various formats.
load The load command allow data to be read from disk files in various formats.
Comments in Octave Language
 A comment is some text that is included in a program for the sake of
human readers, and which is NOT an executable part of the
program.

 Single line comment


 comment starts with either the sharp sign character, ‘#’, or the
percent symbol ‘%’ and continues to the end of the line.

 Block Comments
 Entire blocks of code can be commented by enclosing the code
between matching ‘#{’ and ‘#}’ or ‘%{’ and ‘%}’ markers.
fprint Statements
Opening/closing files for reading and/or writing

Syntax Explanation
fid = fopen (name) mode
fid = fopen (name, mode) ‘r’: open file for reading.
fid = fopen (name, mode, arch) ‘w’: open file for writing. The previous contents are discarded.
[fid, msg] = fopen (…) ‘a’: Open or create a file for writing at the end of the file.
fid_list = fopen ("all") ‘r+’: Open an existing file for reading and writing.
[file, mode, arch] = fopen (fid) ‘w+’: Open a file for reading or writing. The previous contents
are discarded.
‘a+’: Open or create a file for reading or writing at the end of
the file.
fclose (fid) • Close the file specified by the file descriptor fid.
fclose ("all") If successful, fclose returns 0, otherwise, it returns -1.
status = fclose ("all") • The second form of the fclose call closes all open files except
stdin, stdout, stderr, and any FIDs associated with gnuplot.
Examples
Practice Problem
 Write a user defined function file that converts temperature given in oF to
oC, K and R

 Write a user defined function file that converts temperature given in oC to


oF, K and R

 Note the following relationships


9
T(℉) = 𝑇(℃) + 32
5
𝑇( 𝐾) = 𝑇(℃) + 273.15
𝑇 𝑜𝑅 = 𝑇 ℉ + 459.67
9
𝑇 𝑜𝑅 = 𝑇 ℃
5
Practice Problem
Ergun equation is one of the most successful correlations in chemical engineering. It gives the
pressure drop in atm due to flow of fluid in a packed bed as:
150 𝑢0 𝜇 𝐿 1 − 𝜀 2 𝜌𝑢02 𝐿 1 − 𝜀
∆𝑃 = − − 1.75
𝐷𝑝2 𝐷𝑝 𝜀 3
where u0 is superficial velocity in cm/s, L is bed length in cm, µ is fluid viscosity in cP,  is
fluid density in g/cm3, Dp is effective particle diameter in cm, and  is void fraction.
Consider the flow of fluid through a 1 m bed of spherical catalyst particles of diameter (Dp)
= 0.03 cm and void fraction () = 0.35. Write a GNU Octave program that
Prompt the user to provide density and viscosity of the fluid:
I. Calculate the pressure drops in the bed using Ergun equation for flow of fluid at
superficial velocities (u0) in the range of 0.5 cm/s to 15 cm/s at intervals of 0.5 cm/s.
II. Make a well labelled plot of the pressure drop as a function of the superficial
velocity. Use a dashed, red line with a star marker symbol and both axes should be in
logarithmic scale.
III. Test your program with air as the fluid. For air: ρ = 0.00121 g/cm3 and μ= 0.0183
cP.
Practice Problem
Consider a special case of parallel flow involving stationary and moving plates of infinite extent separated by a
distance L, with the intervening space filled by an incompressible fluid. This situation is referred to as Couette flow
and occurs, for example, in a journal bearing. The temperature distribution between the plates is given by

Use Octave to:


•Prompt the user to provide viscosity (µ) and thermal conductivity (k) of the fluid, distance between the plates (L),
speed of the moving plate (U), and the temperatures of the stationary and moving plates (T 0 and TL).
•Calculate the temperature distribution between the plates at values of y ranging from 0 to L mm at intervals of
L/10 mm.
•Make a well labelled plot of the temperature distribution between the plates. Use a dashed, blue line with a circle
marker symbol and both axes should be in rectilinear scale.
•Test your program with engine oil as the fluid. Consider the following specifications: Separation between plates
L= 3 mm, speed of the moving plate is U = 10 m/s, and the temperatures of the stationary and moving plates are T0
= 10°C and TL = 30°C, respectively. The properties of the engine oil (20°C):  = 888.2 kg/m3, k = 0.145 W/m K, v
= 900 x 106 m2/s. µ = v = 0.799 N s/m2
Flow Control
[Conditionals (if, elseif, else)]

If construct If-elseif-else construct


Flow Control: An Example

Write a GNU Octave program that accepts student’s


CGPA and print a message according to the following:
Condition Message
5.00 ≥ CGPA ≥ 4.50 First Class
4.50 > CGPA ≥ 3.50 Second Class Upper
3.50 > CGPA ≥ 2.40 Second Class Lower
2.40 > CGPA ≥ 1.50 Third Class
1.50 > CGPA ≥ 0 Fail
Flow Control
Example: [Conditionals (if construct)]
clear all
clc
CGPA = input('Enter Student CGPA >> ')
if ((CGPA >= 4.50)&(CGPA <= 5.00))
degree_class = 'FIRST CLASS'
end
if ((CGPA >= 3.50) & (CGPA < 4.50))
degree_class = 'SECOND CLASS UPPER'
end
if ((CGPA >= 2.40) & (CGPA < 3.50))
degree_class = 'SECOND CLASS LOWER'
end
if ((CGPA >= 1.50) & (CGPA < 2.40))
degree_class = 'THIRD CLASS'
end
if ((CGPA >= 0.00) & (CGPA < 1.50))
degree_class = 'FAIL'
end
Flow Control
Example: [Conditionals (if, elseif, else construct)]

clear all
clc
CGPA = input(‘Enter Student CGPA >> ’)

if (CGPA >= 4.5)


degree_class = ‘FIRST CLASS’
elseif (CGPA >= 3.5)
degree_class = ‘SECOND CLASS UPPER’
elseif (CGPA >= 2.4)
degree_class = ‘SECOND CLASS LOWER’
elseif (CGPA >= 1.5)
degree_class = ‘THIRD CLASS’
else
degree_class = ‘FAIL’
end
Flow Control
[Loops: for]

The for construct is


for index = expr
The for loop is a loop that
executes a block of
block
statements a specified
number of
end
times.
Flow Control
[Loops: while]

The while construct is


Executes a block of statements
while condition if the condition is true. After
execution of the block,
condition is evaluated again. If
block it is still true, the block is
executed again. This process is
end continued until the condition
becomes false.
Flow Control
[Loops: do-until]

The do-until construct is


The do-until statement is similar to
do the while statement, except that it
repeatedly executes a statement
block until a condition becomes true, and
the test of the condition is at the end
until condition of the loop, so the body of the loop
is always executed at least once.
Flow Control
[Switch]

The switch construct is


switch expression
case value1
block The expression is
case value2
block
evaluated and the control
. is passed to the case that
. matches the value.
.
otherwise
block
end
Example

Problem: Write a for loop that computes the sum 1 + x + x2 + … + xn

Solution
function sumx = myfun(x,n)

% Initialise the sum


sumx = 0

% Compute the sum


for i =0:n
sumx = sumx + x^i;
end
Example

Problem: Write a while loop that computes the sum 1 + x + x2 + … + xn


Solution
function sumx = myfun(x,n)
% Initialise the sum
sumx = 0
I =0;
% Compute the sum
while i<=n
sumx = sumx + x^i;
i=i+1;
end
Example
The roots of a quadratic equation are given by the following
equation:
2
−𝐵± 𝐵2 −4𝐴𝐶
𝑋=
2𝐴
Write a program in Octave that calculates the roots of a
quadratic equation using:
(a) a script file
(b) a user-defined function file
The program should take care of the problem of dividing by zero
or getting a negative number under the square root.
Good Programming Practice
 Use meaningful variable names whenever possible. Use names that can be understood at a
glance, like day, month, and year.
 Create a data dictionary for each program to make program maintenance easier.
 Use only lower-case letters in variable names, so that there won’t be errors due to
capitalization differences in different occurrences of a variable name.
 Use a semicolon at the end of all Octave assignment statements to suppress echoing of
assigned values in the Command Window. If you need to examine the results of a statement
during program debugging, you may remove the semicolon from that statement only.
 If data must be exchanged between Octave and other programs, save the Octave data in
ASCII format. If the data will only be used in Octave, save the data in MAT-file format.
 Save ASCII data files with a “dat” file extent to distinguish them from MAT-files, which have
a “mat” file extent.
 Use parentheses as necessary to make your equations clear and easy to understand.
 Always include the appropriate units with any values that you read or write in a program.
Good Programming Practice
 Follow the steps of the program design process to produce reliable, understandable Octave programs.
 Be cautious about testing for equality with numeric values, since roundoff errors may cause two variables
that should be equal to fail a test for equality. Instead, test to see if the variables are nearly equal within
the roundoff error to be expected on the computer you are working with.
 Use the & AND operator if it is necessary to ensure that both operands are evaluated in an expression, or
if the comparison is between arrays. Otherwise, use the && AND operator, since the partial evaluation will
make the operation faster in the cases where the first operand is false.
 The & operator is preferred in most practical cases.
 Use the | inclusive OR operator if it is necessary to ensure that both operands are evaluated in an
expression or if the comparison is between arrays. Otherwise, use the || operator, since the partial
evaluation will make the operation faster in the cases where the first operand is true.
 The | operator is preferred in most practical cases.
 Always indent code blocks in if, switch, and try/catch constructs to make them more readable.
 For branches in which there are many mutually exclusive options, use a single if construct with multiple elseif
clauses in preference to nested if constructs.
Good Programming Practice
 Always indent code blocks in while and for constructs to make them more
readable.
 Use a while loop to repeat sections of code when you don’t know in
advance how often the loop will be executed.
 Use a for loop to repeat sections of code when you know in advance how
often the loop will be executed.
 Never modify the values of a for loop index while inside the loop.
 Always preallocate all arrays used in a loop before executing the loop. This
practice greatly increases the execution speed of the loop.
 If it is possible to implement a calculation either with a for loop or using
vectors, implement the calculation with vectors. Your program will be much
faster.
Algebraic or Symbolic Computation
 Download symbolic package from Octave Forge
 Install symbolic package using:
 >> pkg install symbolic-2.8.0.tar.gz
 To load the package, run
 >> pkg load symbolic
 Symbolic commands and functions operate on symbolic variables
and expressions that have no predefined numeric value.
 The sym function is used to explicitly define a symbolic variable or
expression.
 The syms function may be used to define several symbolic
expressions at once
Algebraic or Symbolic Computation
 Differentiation of a symbolic expression uses the
diff
 diff(f) : differentiate f with respect to the default
variable x
 diff(f,a) : differentiate f with respect to a.
 diff(f,2) : differentiate f twice with respect x.
 diff(f,a,2) : differentiate f twice with respect to a.
 diff(f,x,y) : differentiate f with respect to x and y.
Algebraic or Symbolic Computation
 Integration (definite and indefinite) of a symbolic
expression uses the int command.
 int(f) : computes the indefinite integral of f with
respect to the default variable x
 int(f,y) : computes the indefinite integral of f with
respect to variable y
 int(f, x, a, b) : computes the definite integral of f
with respect to variable x from a to b.
Algebraic or Symbolic Computation
 Symbolic solution of algebraic equations uses the solve command
SOL = solve (EQN)
SOL = solve (EQN, VAR)
SOL = solve (EQN1, ..., EQNN)
SOL= solve (EQN1, ..., EQNN, VAR1, ..., VARM)
SOL = solve (EQNS, VARS)
[S1, ..., SN] = solve (EQNS, VARS)
 For more details, type
>> doc solve
Algebraic or Symbolic Computation
 Symbolic solution of ordinary differential equations uses the dsolve
command
SOL = dsolve (ODE)
SOL= dsolve (ODE, IC)
SOL = dsolve (ODE, IC1, IC2, ...)
[SOL, CLASSIFY] = dsolve (ODE, IC)

 For more details, type


>> doc dsolve
Example
Xylene, styrene,
toluene and benzene
are to be separated
with the array of
distillation columns
that is shown below
where F, D, B, D1, B1,
D2 and B2 are the
molar flow rates in
mol/min.
Example
 Material balances on individual components on the overall
separation train yield the equation set

 Overall balances and individual component balances on column #2


Example
 Overall balances and individual component balances on column #3

Calculate the molar flow rates of streams D1, D2, B1 and B2.
Example
clear all
clc

pkg load symbolic


syms D1 B1 D2 B2

eq1 = 0.07*D1 + 0.18*B1 + 0.15*D2 + 0.24*B2 - 0.15*70;


eq2 = 0.04*D1 + 0.24*B1 + 0.10*D2 + 0.65*B2 - 0.25*70;
eq3 = 0.54*D1 + 0.42*B1 + 0.54*D2 + 0.10*B2 - 0.40*70;
eq4 = 0.35*D1 + 0.16*B1 + 0.21*D2 + 0.01*B2 - 0.20*70;

sol = solve(eq1,eq2,eq3,eq4,D1, D2, B1, B2)


B1 = double(sol.B1)
B2 = double(sol.B2)
D1 = double(sol.D1)
D2 = double(sol.D2)
Examples
 Use GNU Octave to find the analytic solution of the
nonlinear quadratic equations: ax2 + bx + c.
clear all
clc
pkg load symbolic
syms x a b c
eqn = a*x^2 + b*x + c
sol = solve(eqn,x)
Example: Irreversible Reactions in Series

Consider consecutive unimolecular type first-order reactions such as

whose rate equations for the three components are

Use GNU Octave to


 solve the above system of ODEs
 obtain the particular solution for CA = CA0, CR = CS = 0 at t = 0.
Example: Irreversible Reactions in Series
clear all
clc
pkg load symbolic
syms t k1 k2 cA(t) cR(t) cS(t) cA0 cRo cSo

ode1 = diff(cA(t),t) + k1*cA(t);


ode2 = diff(cR(t),t) - k1*cA(t) + k2*cR(t);
ode3 = diff(cS(t),t) - k2*cR(t);

sol = dsolve([ode1;ode2;ode3])
sol{1,1)
sol{1.2}
sol{1.3}
Example: Irreversible Reactions in Series

clear all
clc
pkg load symbolic
syms t k1 k2 cA(t) cR(t) cS(t) cA0 cRo cSo
ode1 = diff(cA(t),t) + k1*cA(t);
ode2 = diff(cR(t),t) - k1*cA(t) + k2*cR(t);
ode3 = diff(cS(t),t) - k2*cR(t);
sol = dsolve([ode1;ode2;ode3], ...
cA(0)==cA0,cR(0)==cRo, cS(0)==cSo)
sol{1,1}
sol{1,2}
sol{1,3}
Numerical Solutions: Nonlinear Equations

 Solve a system of nonlinear equations defined by the


function fcn.
 fsolve (fcn, x0)
 fsolve (fcn, x0, options)
 [x, fval, info, output, fjac] = fsolve (…)

 For more details, type


>> doc fsolve
Example: Non-linear equations
Find the solution of the following simultaneous clear all
clc
equations
pkg load symbolic

𝑔1 𝑥, 𝑦 = 2𝑥 + 𝑦 − 𝑥 + 𝑦 − 3 = 0 syms x y
5
𝑔2 𝑥, 𝑦 = 4 − 𝑦 − =0 g1 = 2*x + y - sqrt(x+y) - 3;
𝑥+𝑦 g2 = 4 -y - 5/(x+y);

sol = solve(g1,g2,x,y)

x1 = double(sol{1,1}.x)
y1 = double(sol{1,1}.y)
x2 = double(sol{1,2}.x)
y2 = double(sol{1,2}.y)
Example: Non-linear equations

clear all function g = nl_eqns(z)


clc
x = z(1);
% Initial guess y = z(2);
%% z0 = [ 1 1];
z0 = [ 3 -2]; g(1) = 2*x + y - sqrt(x+y) - 3;
g(2) = 4 -y - 5/(x+y);
% Call fsolve
g = g(:);
z = fsolve(@nl_eqns, z0)
endfunction
Numerical Solutions: ODEs

 ODE45 uses a Runge-Kutta (4,5) integration


algorithm to solve ordinary differential equations of
the form
𝑑𝑦
= 𝑓(𝑡, 𝑦)
𝑑𝑡

 The calling sequence for this function is


[t,y] = ode45(odefun_handle,tspan,y0,options)
Numerical Solutions: ODEs
Example 1: ODE Problem

 Employ ode45 to solve the following set of nonlinear ODEs


from t = 0 to 20:
𝑑𝑦1
= 1.2𝑦1 − 0.6𝑦1 𝑦2
𝑑𝑡

𝑑𝑦2
= −0.8𝑦2 + 0.3𝑦1 𝑦2
𝑑𝑡

where y1 = 2 and y2 = 1 at t = 0. Such equations are referred


to as predator-prey equations.
Example 1: ODE Solution

Call File Function File


clear all function yp = predprey(t,y)
clc
% Specify time span and initial values yp = [1.2*y(1)-0.6*y(1)*y(2)
-0.8*y(2)+0.3*y(1)*y(2)];
tspan = [0:0.1:20];
y0 = [2, 1]; end
% Call ODE Solver
[t,y] = ode45(@predprey, tspan, y0);
% Plotting the results
plot(t,y);
xlabel("t");
ylabel("y_1 and y_2");
legend("y_1", "y_2")
Example 1: ODE Solution
Example 2: ODE Problem
The following multiple reactions are to be carried out in a batch
reactor:
k1 k2
R S Q
k3

Write an Octave programme to plot (overlay plots) the


concentration profiles for the components R, S and Q using an
ODE solver. Assume that k1, k2 and k3 are 0.4 min-1, 1 min-1 and
0.3 min-1 respectively, initial concentration of R is 1.5 mol/dm3
and the reaction duration is 25 minutes.
Example 2: ODE Problem
Differential equations

𝑑𝐶𝑅
= −𝑘1 𝐶𝑅 + 𝑘3 𝐶𝑆 ; 𝐶𝑅 0 = 1.5
𝑑𝑡
𝑑𝐶𝑆
= 𝑘1 𝐶𝑅 − 𝑘3 𝐶𝑆 − 𝑘2 𝐶𝑆 ; 𝐶𝑆 0 = 0
𝑑𝑡
𝑑𝐶𝑄
= 𝑘2 𝐶𝑆 ; 𝐶𝑄 0 = 0
𝑑𝑡
Example 2: ODE Solution
clear all function dcdt = odefun(t,c)
clc CR = c(1);
CS = c(2);
tspan = [0 25]; CG = c(3);
y0 = [1.5 0 0];
[t y] = ode45(@odefun, tspan, y0) k1 = 0.4;
k2 = 1;
%Plot Results k3 = 0.3;

plot(t,y(:,1),'r',t,y(:,2),'k',t,y(:,3),'b')
xlabel('time, min') dcdt=[-k1*CR + k3*CS
k1*CR - k3*CS-k2*CS
ylabel (' C_R, C_S and C_G')
k2*CS];
legend ( 'C_R', 'C_S', 'C_G')
Example 2: ODE Solution
Polynomial Fitting
 Return the coefficients of a ❑ Evaluate the polynomial p at the
polynomial p(x) of degree n that specified values of x.
• y = polyval (p, x)
minimizes the least-squares-error • y = polyval (p, x, [], mu)
of the fit to the points [x, y]. • [y, dy] = polyval (p, x, s)
 p = polyfit (x, y, n) • [y, dy] = polyval (p, x, s, mu)

 [p, s] = polyfit (x, y, n) If x is a vector or matrix, the polynomial is


 [p, s, mu] = polyfit (x, y, n) evaluated for each of the elements of x.
When mu is present, evaluate the
polynomial for (x-mu(1))/mu(2).
 For more details, type
For more details, type
>> doc polyfit >> doc polyval
Example: Polynomial Fitting
Use the data in the following table to calculate the
activation energy for the decomposition of benzene
diazonium chloride to give chlorobenzene and nitrogen

Example 3-1 (Fogler, 3rd ed)


Example: Polynomial Fitting
clear all % Calculate activation energy
clc E = -slope*R
% Example 3-1 (Fogler, 3rd ed) A = exp(intercept)
k = [0.00043 0.00103 0.00180 0.00355 0.00717];
T = [313.0 319.0 323.0 328.0 333.0]; t = [T(1):T(end)];
y = log(k); k_pred = A*exp(-E./(R.*t));
x = 1./T; k_Fogler = 1.32e16*exp(-116.5e3./(R.*t));
[p, s] = polyfit (x, y, 1)
figure (2); plot(T,k,'o',t,k_pred,'-b', t, k_Fogler,'--r')
figure(1); semilogy(x,y,'o-r’) xlabel('1/T (K^{-1})'); ylabel('k (s^{-1})')
xlabel('1/T (K^{-1})'); ylabel('ln k ') legend('Experimental','Octave Polyfit','Fogler')
Numerical Integration
 Octave comes with several built-in functions for
computing the integral of a function numerically
(termed quadrature). q = trapz (y)
q = trapz (x, y)
q = trapz (…, dim)
q = quadv (f, a, b)
q = quadv (f, a, b, tol) Numerically evaluate the integral of
q = quadv (f, a, b, tol, trace) points y using the trapezoidal method.
q = quadv (f, a, b, tol, trace, p1, p2, …)
[q, nfun] = quadv (…) q = integral (f, a, b)
q = integral (f, a, b, prop, val, …)
Numerically evaluate the integral of f
from a to b using an adaptive Simpson’s Numerically evaluate the integral of f
rule. from a to b using adaptive quadrature.
Example
Use Octave to evaluate the following integral

∞ −𝑥 2
‫׬‬0 𝑒 ln 𝑥 2 𝑑𝑥

 With symbolic package


 With numerical integration routines
Example
Use Octave to evaluate the following integral

3 1
‫׬‬0 𝑥 𝑠𝑖𝑛
𝑥
1 − 𝑥 𝑑𝑥

 With symbolic package


 With numerical integration routines
Example: Numerical Integration
 For a PFR

 For an entering molar flow rate of 0.867 mol/s,


find the PFR volume necessary to achieve 80%
conversion

 Example 2-3 (Fogler, 3rd ed)


Example: Numerical Integration
clear all
clc
data = [0.0 0.0053
0.1 0.0052
0.2 0.0050
0.3 0.0045
0.4 0.0040
0.5 0.0033
0.6 0.0025
0.7 0.0018
0.8 0.00125];
FA0 = 0.867; % mol/s
X = data(:,1);
rA = -data(:,2); % (mol/dm^3.s)

% Calculate volume
V = FA0*trapz(X, -1./rA)

You might also like