Professional Documents
Culture Documents
CHEN10050
Computational
Methods for Chemical
Engineering
Year 1, 1st Semester, 2017-2018
This unit will provide the grounds for the computational skills using Excel and
MATLAB required for subsequent Chemical Engineering modules
You are supposed to work through the handout during the time designated for
you in a computer cluster and during your own time. Save your programs for the
various exercises in My Documents, a memory stick or any other place where they
can be easily accessed. These stored programs might be useful for the assessments.
Post questions onto the Discussion Board (in the Blackboard page of this
module). Staff and demonstrators will read your questions weekly and will
post back answers. These threads may be seen by all. So, please check if your
question has been already answered before posting a new thread. You are
also encouraged to help answering these questions as well! Please keep in
mind that questions by email will not be accepted.
Module assessment
This module will be assessed through a sit examination at the end of each semester.
Each examination will count 45% of the overall mark. During each semester there
will be also an online test that will count 5% against the overall mark.
In order to practice for these, mock-up online self-assessments will be available on the
BlackBoard page of this module. You can use those to test how well you are doing
and if you are up-to-speed with the material. These tests will not be part of the final
mark for the module.
Exams and online tests will be based on the material delivered during the lecture
sessions, and similar to exercises in the handout and exercise sheets that will be
1
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
released weekly through BlackBoard. You can access and use your programs during
the online tests.
The sessions in the computer clusters will be carried out in separate sessions. The
students are divided in groups; each group should attend the sessions according to the
scheme that will be circulated at the beginning of the semester in the BlackBoard page.
During the sessions on Thursdays, we will be not able to check whether students leave
after their time is up or whether they have come to the appropriate session. Please
remember that there are a limited number of PCs in the cluster room and each of you
should be able to participate to the sessions, so please follow the time schedule. It would
naturally be anti-social and impolite not to adhere to this scheme.
During the second semester, the group arrangement and the times may change.
Additional information on this will be provided in due time.
2
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
Part 1
Microsoft Excel
Topics covered:
Data input and manipulation
Built-in and user-defined functions
Data plotting
Roots of equations using the Solver/GoalSeek tools
Linear and non-linear regression with plots and the Solver tool
3
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
1 Spreadsheeting Exercises
1.1 Introduction
A spreadsheeting package such as Microsoft Excel can help you with many aspects of your course.
Amongst other things, it can organise data, perform calculations and draw graphs for use in reports.
The exercises illustrate some of the things that might prove useful in connection with, say, your
maths, laboratory and project courses.
Save your files on MyDocuments or anywhere you can easily access the files because during
the online assessment you will allowed to use them to solve the exercises.
You are reminded that work submitted for assessment must be the result of your own efforts.
Keep column headings concise - use multiple rows rather than wide columns. As an alternative,
Excel has ways of rotating text and wrapping it to fit available column width. Right click on the cell,
choose Format cells.., then Alignment to see the options available.
Do not use too many decimal places in number formats.
Use the Format, Column, Autofit selection sequence of menu bar commands (Page Layout) to
match column widths to column contents. Beware of the effect of long titles. Restrict the fit to
particular cells by highlighting them. Long titles in a single cell of the column will automatically
overflow into adjacent empty cells.
Arrange the information flow to be vertical rather than horizontal. Page breaks are more natural
that way.
Always use the Preview facility to check that the results are what you expect.
Include your name on each page of output. This makes it easier to find your output among lots of
other similar output. You can use a Header or Footer (a bit of text that automatically appears at the
top or bottom of every page) for this purpose. (In Excel, see Page Layout, and click on the small
arrow on the right of “Sheet Options”.)
1.4 Cells
4
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
Tab
Cell column
Active cell letter
border Formula Bar
HELP
button
Button
Active cell
Cell row
numbers
Enter the values 1, 2, 3 in cells A1, A2, A3. Enter 4, 5, 6 in the next column alongside, then 7, 8, 9 in
the next column.
Cell addresses are used to help manipulate data, perform calculations etc. You can use lower case
letters in cell addresses. Cell b2 means the same as cell B2.
Cell B2 should contain the value 5. To illustrate the use of cell addresses, type =b2 in cell B8, then
press Enter. Note that the formula appears in the formula bar at the top of the screen as you type. Cell
B8 now contains the value 5.
Activate cell B8 by clicking on it. The formula =B2 is displayed in the formula bar as illustrated in
Figure 2.
The active cell has a bold border with a button in the bottom right hand corner. If you click on the
border and move it to another cell the whole contents of the cell moves. If you click on the button and
move that, the instructions in the cell are extended into the highlighted cells.
Use the button on the border of cell B8 to extend the highlighted area into cell B9 – that is, down one
cell. Now click on cell B9 and observe that it contains the formula =b3. A cell address written as B2 is
a relative address. If you drag it down one row it will change to B3. Repeat the exercise by dragging
cell B8 right into cell C8, then click on cell C8 and observe that it contains the formula =C2. Confirm
that dragging cell B8 up one cell produces the formula =B1 in cell B7, and that dragging it left
produces =A2 in cell A8.
The Edit..Copy and Edit..Paste menu commands can also be used to copy cell B8 up, down, left and
right one cell. The results are identical to using the button.
The column or the row or both in a cell address can be fixed by putting a $ in front of it. To illustrate
the effect of fixing the column, enter =$B2 in cell B12. Then drag cell B12 into the adjacent vertical
and horizontal cells. Compare the results with what you did previously. Introducing the $ sign forces
absolute addressing of the column. The part(s) of the cell address preceded by the $ do not change if
you copy the cell to another location.
5
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
Now try fixing the row part of the cell address by typing =B$2 in cell B16 and copying that cell to
adjacent ones.
Finally, fix both row and cell by typing =$B$2 in cell B20 and copy that one into the adjacent cells too.
Review all your results. Introducing the $ sign forces absolute addressing of the column, row or both.
The part(s) of the cell address preceded by the $ do not change if you copy the cell to another
location. It is very important to understand the correct use of cell addresses.
If you are unfamiliar with the 2007 version of Office, you can always use the question mark button on
the top left of the window (HELP button).
Save the spreadsheet as file P:\ex1.xls using the File..Save As... feature from the menu bar.
Excel will automatically add the file name extension .xls. DO NOT type the .xls in the filename.
1.5.1.1 Technique
Use the symbol ^ in a formula to raise to a power.
To use sub- or superscripts, highlight the relevant part of the text, then right click and use the Format
cells.., Alignment options.
To adjust spreadsheet column widths, double click on the dividing lines in the column headings.
6
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
tank is only 80% of its volume so the total tank farm capacity Vtotal is 0.8pq d h/4 m .
2 3
Use Excel to complete Table 1, bearing in mind the lessons of Exercise 1, especially those
concerning absolute and relative cell addresses and copying cells.
Look again at Figure 5. It should be clear that the total area can be calculated in the following way:
The length in the y direction is ly = qd + 2d + (q-1)(d/2) = 1.5(q+1)d.
7
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
The plot appears in the same window (see Figure 4). Right click on the plot area to add labels to the
axis and change the graph characteristics.
Figure 4: Plot
1.5.2.2 Technique
You can type PI() in a formula to obtain an accurate value for (see Functions below).
Use the symbol ^ in a formula to raise to a power
You should only enter the formula in any column once, then copy it into successive rows.
To adjust spreadsheet column widths, double click on the dividing lines in the column headings.
8
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
To get multiple lines of text in a single cell (or group of cells), select the cell(s), right click and use
Format cells.
To use sub- or superscripts, highlight the relevant part of the text, then right click and use the Format
cells.., Alignment options. In axis labels, use Format axis title similarly.
Text size can be changed by right clicking then adjusting the font size.
d/2
d/2
Length
in y
direction
d/2
d/2
Length in x direction
Information Technology
9
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
1.6 Functions
Excel contains many built-in functions. You can see a list by clicking on Formula on the tab and then
click on “Insert Function” on the top left part of the screen as shown in Figure 6. The exercises in this
section illustrate the use of some of these functions.
Figure 6: Functions
Create a table of values, including column titles. The first column should contain the angles 0, 15,
30, ... , 360. You do not need to type all these values individually. First type a title (for example,
Angle, degrees) in cell A1. Type 0 in cell A2, then 15 in cell A3. Highlight cells A2 to A3. Drag the
highlighted cells down using the button and observe that final value is displayed as you do so.
Keep dragging until the final value is 360. Excel assumed that you wanted to create a series of
numbers incrementing by 15.
10
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
The trigonometric functions only work for angles in radians, not degrees. A conversion function is
available. If the first cell in your list of angles is cell A2, enter =radians(A2) alongside it in cell B2.
Put an appropriate title in cell B1.
Select cell C2. Type = then click the “Insert Functions” button in the Formulas box in the tab. Type
“sin” then click on go. Figure 7 shows what happens next (only one row of the table is shown)
Click the button shown in Figure 7. A small selection window will appear. Highlight cell B3 to
indicate that is what you want to take sin of. Press OK to complete the selection.
Make an XY plot of sin versus angle in degrees.
Highlight all 25 rows of numerical data in column A. Press the Ctrl key and highlight the same 25
rows of column C. Both column A and column C should now be highlighted.
Click on “Insert” in the tab.
Choose the Scatter in the chart option, then the variant that plots smoothed lines.
Click on “Select Data” on the tab, select “Series 1” and then “edit”. Name the series as sin. (see
Figure 8)
Add the labels for the x axis (Angle/degree) and the y-axis (Function value) and the plot title (SIN
function), clicking on “Chart Layouts”.
Extend the table to include cos and tan. Make the chart display sin, cos and tan simultaneously as
separate series. Do NOT produce three separate charts. Click again on “Select Data” and click on
“Add” button.
nd
Add the title of the new series of data. To enter the data click the 2 button (for X values). Another
pop-up appears. Highlight the data in cells A2 to A26 then press the coloured button to return to
rd st
Figure 8. Click the 3 selection button to choose cells D2:D26 as the Y values. You could use the 1
selection button to get the series name from cell D1 in a similar way – but it might be just as easy to
type cos in the box.
Note the way Excel refers to a range of cells. D2:D26 means all the cells starting from D2 up to and
including D26. (Similarly H1:K15 would refer to a whole oblong block of cells with H1 at top left and
K15 at bottom right.)
11
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
Graphing tan creates problems because it gets very large as the angle approaches 90 (and 270)
degrees, then becomes very large and negative as the angle increases beyond 90 (and 270) degrees.
Adding tan into the plot as a single series is NOT satisfactory.
Change the y-axis scale to ± 3 so that the sin and cos curves are clearly visible. Do this by right
clicking on the y-axis and navigating through the menus that appear.
Tidy up the plot by setting an appropriate x-axis scale, tick marks at 15 degree intervals on the x-axis
and 0.1 intervals on the y-axis, etc.
Tidy up the table by arranging that it displays radians, sin, cos and tan to four decimal places. To do
this, highlight the relevant columns, right click and choose Format cells…, Number… then choose
Number and set decimal places to 4 on the form that appears.
12
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
expression several times in the spreadsheet. To enable the creation of custom functions go to
FileOptionsCustomize Ribbon and select the option Developer, as indicated in Figure 9, and
press OK.
Figure 9: Enabling custom functions editing
In the Developer tab of Excel’s ribbon, select Visual Basic to open the function editor. Next, in the
menu bar of the new window, select InsertModule. The custom function should be typed in the new
window that will pop-up and should have the following structure:
Function function_name(argument1, argument2, …)
function_name = mathematical_expression
End Function
2
For example, the function called myfunction expressed mathematically as ax +bx+c has as the
arguments a, b, c and x, and should be written as:
Function myfunction(x, a, b, c)
myfunction = a*x^2+b*x+c
End Function
13
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
Close the editor window and test the function in Excel. The myfunction function can now be used
as any Excel predefined function by typing myfunction() in a cell of the spreadsheet. Try plotting the
custom function for different values of x and for constant values of a b and c, as shown in Figure 11.
Important note: Workbooks that contain custom functions should be saved as Excel Macro-Enabled
Workbooks to work properly once they are re-opened. These files have extension .xlsm.
Goal Seek is efficient but not very powerful; to find the root of the equation and needs to have a target
cell that is close to the actual root of the equation. Therefore, plot the function in a range of data (for
example in Figure 9 from 1.5 to 4) and identify the three roots. Click on the Data tab and on “What-If-
analysis” and then fill the form of Goal Seek. The Set Cell in the example case is C5 since this
contains the function expression. We want it set equal to zero by varying the value in cell B5. Click
14
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
Ok. The estimate of the root and the corresponding value of f(x) should replace the original values.
Repeat this procedure for all the roots of your equation. This means you should know in advance how
many roots your equation has!
15
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
1.8.1.1 Technique
Figure 13 shows part of the spreadsheet.
2
Use the Help facility to obtain an explanation of trendline equations and the meaning of R .
Right click on the data points on the chart to obtain the trendline option. Within the trendline dialogue,
2
choose the options to display the equation and R value on the chart.
When the trendline equation is displayed, right click on it and format the labels to display in scientific
format with 6 decimal places.
You can copy coefficient values from the displayed equation into spreadsheet cells using Edit..Copy,
Edit..Paste. Take care not to lose the sign when copying negative values.
16
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
When you have a set a data that you want to fit with a specific equation (derived from a theory for
example), there is another tool of Excel called Solver that can help you. Solver works with a group of
cells that are related to the formula in the target cell. Solver adjusts the values in the changing cells
that you specify — called the adjustable cells — to produce the result that you specify from the
objective cell formula.
First of all check that Solver has been installed in your computer. Click on the Data tab, Solver should
be on the Analysis group (Figure 14). (If Solver does not appear in the Analysis group, you need to
add the solver Add-in program. Click the File tab, and then click Options, click Add-Ins, and then in
the Manage box, select Excel Add-ins. Click Go.)
So if you want to fit your data against the Clausius-Clapeyron equation (eq. 1), Solver can be used to
adjust the values of A and B
B
log10 P A (eq. 1)
T 273.15
to the vapour pressure data of Table 2. To do this, you need to minimise the sum of squares of the
error (SSE) between the data and the fitted equation. For a set of estimated values ŷ i of data points
y i , i = 1,…,n.
n
SSE yi yˆi
2
i 1
17
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
SSEmean SSE
R2
SSEmean
where SSEmean is the total sum of the squares of the residuals between the data points and its mean
value, y , defined as
n
1 n
SSEmean yi y and y yi
2
i 1 n i 1
The coefficient of determination can be interpreted as a normalized measure of how good the fitting
expression is in describing the variability of the data in opposition to simply assuming the mean value
R 2 1 . When the fitting expression does not
of the data. For a perfect fit, SSE 0 giving a value of
represent any improvement, SSE SSEmean resulting in R 0 .
2
1.8.2.1 Technique
Figure 11 shows part of the spreadsheet.
Enter the raw data and calculate log10P.
Enter the first guesses for constants A and B in two spreadsheet cells. Calculate the corresponding
estimates of log10P given by the Clausius-Clapeyron equation.
18
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
SSEmean can be calculated in the same way as SSE by entering the formula =SUM((E12:E21-
AVERAGE(E12:E21))^2) and pressing Ctrl+Shift+Enter.
2
[solutions: A=8.75, B=2035.17, R =0.992]
19
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
Part 2
MATLAB 1
Topics covered:
Introduction to the MATLAB environment
Types of variables and number formats
Mathematical operations
Built-in MATLAB functions
Graphical display of data
MATLAB programming
o m-files structure
o Writing programs and user-defined functions
o Structured programming with if-structures and loops (for and
while)
20
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
In this course we will explore some features of the MATLAB programming language and
use these to solve some numerical problems. These notes are what you will need in order to
do the online assessment in December.
To help you do this test, you are advised to work through all the exercises and save your
programs onto My Documents and/or a pen drive.
Otto S.R. and Denier J.P. (2005). An Introduction to Programming and Numerical
Methods in MATLAB, Springer.
Lindfield G.R. and Penny J.E.T. (2012). Numerical methods using MATLAB®,
Elsevier.
They can be accessed online for free through the UoM library website or the Blackboard page
of this module if your computer is on campus. Do note, however, that there are plenty of
other books in the library on MATLAB programming and also plenty of online help.
You can start MATLAB the start menu. Click on All Programs MATLAB
MATLAB2015b
A window should pop up and start MATLAB.
It is not possible to download and use MATLAB from home using the University Licence.
You can, however, access the program from ANY of the computer clusters on campus.
Online help is available from the MATLAB prompt (a double arrow), both generally (i.e.,
listing all available commands) and also for specific queries:
>> help
[a long list of help topics follows]
The answer to the most popular question concerning any program is this: leave a MATLAB
session by typing
quit
21
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
or by typing
exit
1. Getting going
MATLAB is an easy-to-use and powerful system for solving mathematical problems. The
name stands for MATrix LABoratory, as the system is designed to make matrix calculations
easy.
Note you can always edit by using backspace, del and the various arrow keys.
Hopefully all the arithmetical operations are pretty obvious. NaN, by the way, stands for
“Not a number”!
More information
Operation Symbol
Addition +
Subtraction -
Multiplication *
Division / or \
Exponentiation ^
MATLAB has two division operators / - the right division and \ - the left division. They do
not produce the same results
rd = 47/3
rd =
15.6667
ld = 47\3
ld =
0.0638
22
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
(i.e. rd=1/ld)
You should read “=” as “becomes”. Thus when obeying the command
a = a + 2
the computer takes the old value of a (i.e. 3), adds 2, and re-assigns the result (5) to the
variable a.
Answer: It means that nothing is printed to the screen – i.e. output is suppressed.
As you will see later, suppressing output can be very useful, for otherwise you can be
swamped with seeing far too many numbers on the screen!
x = 5
y = 3
z = x + y
z =
23
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
Q2: Without typing anything into MATLAB, work out the final values of x, y and z from
the lines below. Then type the commands in and see if you are right! Obtain the values of
the variables by typing x, followed by y, followed by z.
x = 2;
y = -1;
z = 4;
x = z/x;
z=z^x;
y = y – x + z;
Q3: What would be the final value of sum from the lines below? Work it out first and then
check if you are right by typing the commands into MATLAB
sum = 0;
sum = sum +1;
sum = sum + 2;
sum = sum + 3;
sum = sum + 4;
Note log(x) in MATLAB means loge(x) (which is the same as ln x), exp(x) = ex and log10(x)=
log10(x)
Note the angle for sin, cos, tan, etc is taken to be in radians. pi is .
i) sin (0.25)
ii) ln(5)
iii) e3.6
iv) sin(51o)
v) sqrt(3.5)
(iv) There are several different formats you can use in MATLAB, which change the way in
which a number is written.
format short
format long
format short e
24
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
format long e
format compact
Q5: Type
format short
a = 1/300
Then try
format long
a = 1/300
When you use format short e or format long e, MATLAB writes out the numbers in
scientific notation.
MatLab also uses this output for format compact for numbers that are large or small.
This does not, however, wipe out the values and types of previously defined variables.
To start completely afresh, type clear. This is like starting again from the beginning.
When you get strange error messages, one possible cure is to type clear and try again!
(v) So far we have used scalars – i.e. they have one value. MATLAB also handles arrays (or
vectors). These are lists of numbers.
Type:
a = [2, –5, 1.2, 0.1];
a
25
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
“a” is list of four numbers. You can imagine a having four boxes with a certain number in
each box, i.e.
2 –5 1.2 0.1
a(2)
These arrays can be very useful in programming and you also need them to do plots.
2. Plots
Suppose you want to plot sin(x) vs x. You need an array, x, containing the x- points and an
array, y, containing the corresponding value of sin (x).
x = [0, 1, 2, 3, 4, …];
x = 0 : 10;
Now type:
y = sin(x);
y =
26
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
x = 0 : 0.1 :10 ;
y = sin(x);
Now try:
plot (x, sin(x) ) , grid
x = 0 : 0.1: 2 ;
y = x ^4 ;
y
When using arithmetic operators (like ^, * , /) on arrays (i.e. when you want to do the same
operation on each element), you need to replace them by
(. ^, .* ,. /)
y = x .^4 ;
y
x = -2: 0.1: 2;
y = 2*x.*x – 3*x +1;
plot(x,y)
Note that multiplying an array by a constant number (e.g. the 2 or the 3) or adding a constant
(i.e. the 1), does not require any dot operator.
27
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
x = -2: 0.1: 2;
y = x.*sin(x);
plot(x,y)
i) y = cos(x) 0<x<2
Suppose you have £1000 in your bank and you get interest of 9% each year. What is the
balance at the end of the year? We’ll write a program to work it out.
Go into the editor (either via the blank sheet icon or File | New | M-file ).This is a scratch-
pad for writing programs.
Notes
a) The words after % are comments. The computer ignores them, but they can be useful for
helping someone (e.g. yourself, several days after writing it!) understand what a program is
doing.
b) It is good practice to call the variable sensible things that reflect what the quantities are.
28
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
e) disp( ‘new balance:’ ); prints out the text new balance. That is what happens when you use
quotation marks (‘ …’).
f) disp( balance) ; prints out the number assigned to the variable balance.
Later on you will find more sophisticated ways of printing things out.
Select, copy and paste the program to the Command Window and press enter.
If there is a mistake, return to the editor to make the corrections and then cut and paste back
into the Command Window.
- Inputting data-
If you wanted to use this program with a different starting balance or a different rate of
interest, you would have the change the program and run it again.
It is possible, however, for the program to read data you type in on the screen.
Try the following:
value of balance:
appears on the screen is the number assigned to the variable balance. A similar thing happens
with the variable interest.
29
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
To save this program, go to the editor and select File | Save as from the tool-bar. Select a
directory (e.g. MyDocuments) and enter the file name compint.m. (it must be of the form
*.m).
Now enter compint in the Command window. This will run the compint program only if
your current directory is “MyDocuments” (see next section)
To run a script, make sure that the current folder (see the tool bar at the top of the command
window)is the folder that contains your file. Thus if you have saved compint.m to a folder
called EC within MyDocuments, the current folder box should contain something like
If, as is very likely, something else appears in that box, click on the box containing three dots
(i.e. …) to the right of the current folder box. A drop-down menu will appear which will allow
you to select the folder you need.
To run a program:
Select the file in the Current Directory Browser (a screen, not the icon mentioned above!).
Do the following exercises, making sure you save the programs in My Documents and/or a
memory stick.
a x + b = 0,
Q11: Write a program to calculate the surface area and volume of a sphere ( 4r 2 and
4r 3 / 3 respectively), for an input value of r of your choice.
ax 2 bx c 0
30
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
for input values of a, b and c of your choice. Print out the two solutions and also the value of
(b 2 4ac)
Note:
What does MATLAB give for 2/5*4? Is it (2/5)*4 or 2/(5*4) ? Try it and see!
[ans =
1.6000 ]
Still, in order to be sure the computer is doing what you intend, it is best to use brackets. Thus
the formula for the solution to a quadratic equation may best be written
x b b 2 4ac /( 2a)
Also note that you must put in the multiplication symbol (*) in Matlab! Thus Matlab will
require 4*a*c and 2*a !
- Transposing arrays/vectors. -
So far we have set up “row” vectors. Sometimes we need a “column” vector. This is
especially helpful for printing out a table of date.
Type:
x = 1 : 5
x’
1 2
Q13: Vertical motion under gravity (the equation to implement is s ut gt )
2
31
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
Check it carefully, the copy and paste it to the command window and run it.
Make sure you understand what is going on! MATLAB’s ability to rapidly manipulate lists
of numbers and then plot them is a very powerful feature.
Note
2) s is also a row vector, containing the height corresponding to the times in t. Thus s(1) is
the height at time t(1), s(2) is the height at time t(2), etc.
6) the ellipsis (…) joins the current line up with the following one.
Q14: The equation of motion of a simple harmonic oscillator, initially at rest, is:
x = a cos(t)
Set a = 2 and = 5. Write a program to generate a labelled plot of x vs. t for t in the range
0 – 3 and also produce a table. Take the time increment to be 0.1.
[A] = [A]0exp(-kt)
where [A]0 is the initial concentration and k the rate constant. Set k = 2 and [A]0 = 3. Write
a program to generate a labelled plot of [A] vs. t for t in the range 0 – 2 and also produce a
table. Take the time increment to be 0.05.
Note: MATLAB will not allow you to use [A] as a variable – the square brackets are not
allowed! You must call the concentration something else in your program – e.g. A.
[ A]0
[ A]
1 k[ A]0 t
32
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
MATLAB can produce graphical plots of series of data (using the command plot) or
functions (using the command fplot).
x =[1,2,3,4,5,6,7,8,9,10]
y =[1,4,9,16,25,36,49,64,81,100]
plot (x,y)
Click the white arrow (“Edit Plot”) from the bar and double click on the white space in the
graph. This enables the property editor. Now you can create or modify such things as the
labels of the axes, the upper and lower values marked on the axes and the grid.
33
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
If you want to plot a specific function you can use the command fplot
fplot (‘sin(x)’,[-pi,pi])
You can change the interval of the plot either changing it in the fplot command
fplot (‘sin(x)’,[0,pi])
fplot ('4*x^3-2*x^2-200*x-50',[-10,10])
Playing with the tools menu in the graph window you can find the approximated roots for the
equation 4x3-2x2-200x-50=0.
As an example, one of the three roots may be found from the plot shown below.
34
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
Q17: Use fplot to plot exp( x) x in the range -1 < x < 2 and then use the tool menu so as
to obtain the root accurate to two decimal places.
[Ans. 0.57]
[Ans. 0.65]
Often it is useful to plot several data in one single graph. The command plot of MATLAB
can do this easily.
Q14. The equation of motion of a simple harmonic oscillator, initially at rest, is:
x = a cos(ωt)
Set a = 2 and ω = 5. Write a program to generate a labelled plot of x vs. t for t in the range
0 – 3 and also produce a table. Take the time increment to be 0.1.
Suppose you want to graphically verify what is the effect of the value a on the shape of the
function. You can then create another array, say y, of values
y = a cos(ωt)
setting a=5 and ω=5 and then plot the two functions together simply typing
plot (t,x,t,y)
35
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
You can play with the colour of the lines as well. For example if you want the first set of data
in blue and the second in red you can type
plot(t,x,’b’,t,y,’r’)
10000
1 1 1 1 1
n 1 2 3 10000
n 1
sum = 0;
sum = sum +1/1;
sum = sum + 1/2;
sum = sum + 1/3;
sum = sum + 1/4;
…
sum = sum +1/10000;
disp(‘sum is’);
disp(sum)
Fortunately MATLAB allows you to do things like this very easily, using the for end
construction. This is a loop. Loops are at the very heart of computing. It is not always easy to
get the hang of them straightaway, but please persevere – the effort is well worth it!
36
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
for n = 1:5
disp (‘In the loop. Iteration number: ‘)
disp(n)
end
disp(‘Just exited from loop’);
disp(‘final value of n );
disp(n);
The loop begins with for n = 1:5 and finishes with end
In the loop. Iteration number: and then writes out the current value of n (i.e. 1).
The computer then goes back to the beginning of the loop and sets n = 2. It again prints out
In the loop. Iteration number: but this time the current value of n is 2.
This loop keeps on going, each time increasing the value of n by 1, until finally we reach n =
5. This is the final time through the loop and after writing out the data for the 5th and final
time, the computer exits the loop and then prints out
It may be that you do not want to start with n = 1, or you may want n to change each time by
an integer different from 1, or you may want to count down.
Q19: Edit the program above, replacing the for line with
37
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
n 1 2 3 4 5
n 1
We can do this by combining the for end construction with the program in Q3:
Note: make sure in MATLAB you use a single quotation mark in disp. The disp line should
look purple in the MATLAB editor!)
1 1
2 3
3 6
4 10
5 15
Just exited from loop
final value of n and sum
5 15
Each time we go round the loop, the computer adds the next term in the series to sum.
10
a) n 1 2 3 4 5 9 10
n 1
38
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
10 55]
15
b) n 5 6 7 14 15
n 5
10
c) (3n) 3 6 9 27 30
n 1
(Do this using a for end loop, going up in steps of 3)
10
1 1 1 1 1
n 1 2 3 10
n 1
We have the same program as before, but this time instead of adding n to the sum each
iteration, we add 1/n, e.g
15
1
a) n
n 1
[15.0000 3.3182]
15
1
b) n [15.0000 1.2349]
n 5
15
1 1 1 1 1
c) (2n 1) 3 5 7 31 [15.0000 1.3681]
n 1
39
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
15
1 1 1 1
d) n
n 1
2
12
2 2
2 15 [15.0000 1.5804]
10
e) 2
n 1
n
[10 2046]
Of course you can do more than sums with the for end construction. Here is a program to
calculate factorials, in particular 10!, where
Often a program branches, depending on whether two numbers are the same, or whether one
exceeds the other. These tests use relational operators. Here are some of those used in
MATLAB:
40
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
x = 2;
if x < 0
disp( 'neg' )
else
disp ( 'non-neg' )
end
Did you get the non-neg message? Repeat the exercise, this time with x = –1.
This is the basic if – else – end construction. You must remember to put in end, or MATLAB
will wait forever!
Now try:
x=2;
if x=2
disp(‘ x equals 2’)
else
disp(‘x is not equal to 2’)
end
The problem is that the line: x = 2, means that x is assigned the value of 2 – it is not a test for
equality. Looking back at the table of relational operators, what change must you make to get
this program to work?
Suppose, however, you wanted to do a random walk on a square lattice. An efficient way to
do it makes use of the elseif construction.
Try this:
41
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
Run this a few times to check you see how it works. Note that if, for example, r = 0.1, so r <
0.25, then you only get the ‘move left’ message, even though r < 0.5, etc. as well!
Ex. 10: Modify this program so the particle does a random walk on a cubic lattice – i.e. each
step can be along one of three perpendicular directions, so there are a total of six possible
steps.
Ex. 11: Write a program to solve the quadratic equation ax 2 bx c 0 , where the values
of a, b and c are read into the program.
Then use an if construction, so that if disc < 0, the program prints out “No real roots”, but
otherwise calculates the two roots and prints them out.
Ex. 12: Strictly you should also allow for the possibility disc = 0 and there is only one root.
Use an if …elseif … end construction to allow for this.
Ex. 13: One way to solve non-linear equations is to use a numerical method called the
bisection method (you will do this later in your mathematics unit). A key element of the
routine is to call a function, f(x), at two points – x1 and x2 – and decide whether the product
f(x1)*f(x2) is positive or negative.
Then write a main program in which you enter x1 and x2. You then use an if construction , so
that if fun(x1)*fun(x2) > 0, you write “positive product”, else you write “negative
product”.
6) While loops
Sometimes you do not know how many times you will need to repeat some lines of program,
so a for – end loop is not well-suited for the task.
For example, suppose you had £1000 in an investment and the compound interest on it was
10%. How many years must you wait for the investment to double?
42
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
The program keeps on advancing the years and adding on the interest until the statement bal
< 2*a is false, whereupon the loop ends.
1 1 1
Consider the series n 1 2 3
n 1
Use the while-end construction to find the
minimum number of terms you need in this series for the sum to be greater than 3.
Again the loop keeps on going until the condition sum < 3 is false. The last value printed
gives the sum and the value of n when the sum first exceeds 3.
Ex. 14: A population of bacteria doubles its size every hour. Starting from 1 bacterium at
time 0 hours, how many hours are needed for the population to first exceed 1,000,000 ? Use a
while … end loop to do this.
the minimum number of terms you need in this series for the sum to be greater than 100,000.
(n = 67 sum = 102510)
43
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
Now that we have understood the while …end construction, we can return to the trapezium
rule programs and answer the question about how to calculate an unknown integral to a
desired level of accuracy.
We return to the program you wrote for ex. 7 and we are integrating f(x) = 1/x. We now use
the while construction, so that the computer keeps on doubling n until the value of the error
gets less than a user defined tolerance, tol. What value of n is needed, for example, to get the
error less that 1.0e-3, 1.0e-6 or 1.0e-8 ?
44
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas
The exam in January will be based on all the topics covered during the lectures and in
this booklet…
However, do not throw away this booklet after the exam! You will need it to continue
the course in the second semester.
45