You are on page 1of 46

School of Chemical Engineering and Analytical Science

CHEN10050
Computational
Methods for Chemical
Engineering
Year 1, 1st Semester, 2017-2018

A. Alfutimie & R. Villegas


University of Manchester
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas

School of Chemical Engineering and Analytical Science


CHEN10050
Computational Methods for Chemical Engineering
Year 1, Semester 1, 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.

 In case of problems while working through the handout:

 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.

 Demonstrators will be available in the Simon Building and James Chadwick


Building computer clusters on Thursdays 10.00 – 12.00 for face-to-face
interaction. (During the 1st semester, 2nd semester still to be decided)

 There will be weekly office hours


 Dr Abdullatif Alfutimie (Office B9, the Mill) on Thursdays from
2pm to 3pm
 Dr Rossmary Villegas (Office C46, the Mill) on Thursdays from
12pm to 1pm

 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.

Exams and online tests will be run through Blackboard.

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.

Note for the computer cluster sessions on Thursdays:

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.

Further information on the organization of the sessions will also be available on


Blackboard and might be circulated via email.

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.

1.2 Using Excel


 Excel is available from the Windows Start button -> All programs -> Microsoft Office .
 Figure 1 shows a typical Excel window.

1.3 Printing your results


Although you have not got any results yet, it is important to think about printing them. If you plan
ahead, the spreadsheet layout can usually be organised to give a pleasing appearance when printed.
The secret of successful printing is to design your spreadsheet from the outset to fit A4 paper. A4
paper is 21 cm wide by 29.7 cm long. A left margin of at least 2.5 cm is usually required to allow for
binding, hole punching, etc. The right margin should be at least 1 cm and top and bottom margins
about 2.5 cm each. The effective printing area is thus no more than about 17.5 cm by 25 cm. It is
usually the width restriction that causes the most trouble. Although Excel allows landscape printing
(that is, the paper is turned sideways), it is preferable to use portrait layout in reports if possible. The
following simple guidelines may help:

 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

1.4.1 Exercise 1: Absolute and relative cell addresses.


The main area of the Excel window is split up into cells. Figure 1 shows a screenshot of a typical
Excel window. Each cell is identified by its cell address consisting of the column letter and row
number. The column letters appear just above the cells and the row numbers appear to the left of the
cells. You make a cell active by clicking on it with the mouse. Once a cell is active you can type in
data, then press Enter.

4
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas

Figure 1: Typical Excel window

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 Formulae and graphics


Formulae are used to perform calculations in a spreadsheet. Figure 2a shows a screenshot of some
simple examples. Figure 2b shows how formulae were used to produce the results. You would not
usually see the version in Figure 2b on the screen, but you can switch to it (and back again) by
pressing the Control key and the ` key (first button on the left top in the keyboard) together (usually
shown as Ctrl+` in manuals). Formulae use cell addresses to make sure the right things are added,
subtracted, multiplied etc. Thus in the addition example the contents of cells b4 and b5 are added
together. Note that all the entries in column A of Figures 2a, 2b are just descriptive text. Typing a+b in
cell A6 does NOT cause any calculation to take place! Cell B4 contains the value of a, cell B5 the
value of b and the formula =B4+B5 in cell B6 causes the addition of these two values. Note that the
formula must begin with the = sign.
Do these calculations in your own spreadsheet.

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

Figure 2a: Basic arithmetical operations Figure 2b: Formula view

1.5.2 Exercise 2: The tank farm


This example develops the use of formulae and cell addresses in spreadsheets. It also introduces
graphical display of data.
Crude oil is to be stored in cylindrical tanks before it is refined. The tanks are laid out in the pattern
shown in Figure 5 with p tanks in the x direction and q tanks in the y direction. Tank diameter, d, is 32
m. Tank height, h, is 10 m. The volume of one tank is d h/4 m , but the usable capacity of each
2 3

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.

 The length in the x direction is lx = pd + 2d + (p-1)(d/2) = 1.5(p+1)d.

 Tank farm area A = lxly.

1.5.2.1 Graphical display of the data


Use the ChartWizard button to create an X-Y scatter chart of usable capacity against area. Plot the
points without any connecting line. Highlight the two columns of data as shown in Figure 3, go to the
Inserttab press the button highlighted in yellow the Figure.

7
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas

Figure 3: Chart Wizard

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.

Figure 5: Tank farm layout

Tank Farm Layout


p=4, q=5

d/2 d/2 d/2


d d

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

Table 1: Relationship between tank capacity and tank area


Tank diameter, d m
Tank height, h m
Number of tanks Number of Tank farm area Total usable tank
2
in x direction tanks A, m capacity
3
p in y direction Vtotal, m
q
4 4
4 7
4 8
4 9
4 10

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

1.6.1 Exercise 3a: Trigonometric function plot.


To illustrate the use of functions, chart the trigonometric functions. Evaluate the functions at 15
degree intervals in the range 0-360 degrees.

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

Figure 7: Selecting cells for functions

Insert the cell to be used

 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

Figure 8: Adding another series

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.

1.6.2 Exercise 3b: More functions


The file Nwproducts.xls contains data on a range of products available to order from a distributor.
These data are taken from a sample database file supplied by Microsoft for use with Access. Because
of this the entries in the Unit price column are in text form and cannot be used to perform calculations.
Use the Text functions LEN(), RIGHT() and VALUE() to convert these text entries into numerical
equivalents in a new column. You can even format the numerical values to display a $ sign by
choosing a currency format for the cells. Descriptions of LEN(), RIGHT() and VALUE() can be found
by selecting these functions from the menu. They are used here to remove the leftmost character ($)
from each entry then convert the remaining text to a number.
Use the COUNTIF Statistical function to count how many discontinued products there are.
Use the Statistical functions MAX, MIN and AVERAGE to find the maximum, minimum and average
values of unit price and units in stock.
Use the Math and Trig function SUM to calculate the total number of units in stock and units on order.
Finally, sort the table into ascending order of Supplier ID number. This is not done using functions.
You need to select the entire table of data then choose Data, Sort from the menu bar and fill in the
forms appropriately. NB do NOT sort only the Supplier column!

1.6.3 Exercise 3c: Creating custom Excel functions


It is also possible to develop our own custom functions in Excel. These function are written in a
relatively easy to learn and use programming language called Microsoft Visual Basic. Custom
functions might be quite helpful, for example, to avoid typing long and complex mathematical

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
FileOptionsCustomize 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 InsertModule. 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

as also shown in Figure 10.


Figure 10: Custom functions editor

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.

Figure 11: Custom function use in Excel

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.

1.7 Roots of equations


The roots of any function f(x) are the values of x that make f(x) = 0. Excel can find real roots in at least
two ways - by plotting the function and by solving the equation. Finding complex roots is another
3 2
story. Figure 9 illustrates both ways of finding the roots of f(x) = x + 3x - 3. Because the function is
cubic (highest power of x is three) it must have three roots, r 1, r2, r3.
First tabulate the function over some suitable range of values of x, probably chosen by trial and error.
Use this tabulation to produce an XY scatter plot. The function roots can be determined approximately
by observing where the function value is zero. If no roots are found, adjust the range of values of x.
The roots can be determined more accurately by solving the equation f(x) = 0. There are many ways
of doing these using numerical methods. Some will be described in your mathematics course. Whilst it
is valuable to understand how the calculations can be performed, it is also helpful to have a tool that
will do them for you. Excel 2010 has an analysis tool (Goal Seek) that does just that. Goal Seek
adjusts the values in the changing cells that you specify in “Set Cell” to produce the result that you
specify in “To Value” changing the values in the cell you specify (Figure 9). You can find this tool in
the Data tab, “What is Analysis”. (* Note here that these instructions are valid for Office version 2010.
Previous versions of Office used another tool called Solver, see also exercise 5.2, to find the roots of
equation. The modified version of Solver in Office 2010, cannot be used for this purpose anymore.)

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!

1.7.1 Exercise 4: Roots


3 2
Find all three roots (r1, r2, r3) of f(x) = ax + bx + cx + d using both the graphical method and Solver.
Arrange your spreadsheet so that it is easy to change the values of a, b, c and d. Test your
spreadsheet using a = -0.3, b = 0.8, c = 4, d = -7.5.
You need to choose your starting guesses in Goal Seek carefully to ensure that all the different roots
are found. Your XY chart should help with these choices.

Figure 12: Roots of a cubic equation

1.8 Regression and curve fitting


Engineers often perform experiments to obtain data. In order to use the data in subsequent
calculations it can be very helpful to find an equation that draws a curve through the data points.
Depending upon the quality of the data and the type of calculations to be performed, the equation may
need to fit the data more or less accurately. Sometimes the form of the equation might be determined
by theoretical analysis. In other circumstances there may be little theoretical justification other than
that the equation reproduces the given data in an acceptable way. This exercise illustrates some of
the many techniques for fitting equations to data. More detail will be given in your mathematics
course.
Table 2 contains some vapour pressure data obtained by experiment. An equation is required so as to
use these data in subsequent calculations.

15
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas

Table 2: Vapour pressure data


Temperature, T Pressure, P
C mm Hg
-36.7 1
-19.6 5
-11.5 10
-2.6 20
7.6 40
15.4 60
26.1 100
42.2 200
60.6 400
80.1 760

1.8.1 Exercise 5.1


Read section 1.8.1.1 before attempting this exercise.
Enter the data of Table 2 into Excel. Produce an XY (scatter) chart showing P on the y-axis versus T
C. Use linear axes, with x-axis scale –40 to 100 and y-axis scale 0 to 800. Make the y-axis cross the
o
x-axis at T = -40 C. Include appropriate chart and axis titles including units.
Use the chart trendline facility in Excel to fit polynomials

P  a0  a1T  a2T 2  ...  amT m


of order m = 3 and m = 4 to the data of Table 2. Display the trendline equations in scientific notation
with six decimal places. (For example, 0.000123456 should be displayed as 0.123456E-03).
Note: by default Excel gives the trendline equation as y = f(x), and you should always edit the
equations to use the correct symbols, in this case P = f(T).
Use the trendline equations in the spreadsheet to re-calculate estimates Pestimate of P in each case.
Display the estimated pressures to 2 decimal places. Hence calculate the relative percentage error in
the estimated values ((Pestimate-P)*100/P), display to three decimal places).

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

Figure 13: Example

1.8.2 Exercise 5.2


Read section 1.8.2.1 before attempting this exercise.

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

Use A=B=1 as your first starting guess.


Calculate the vapour pressure values predicted by the Clausius-Clapeyron equation using the values
of A and B you found.
Calculate the percentage errors with respect to the original values. Additionally, the coefficient of
determination, R 2 , can also be used to quantify how good the fitting is. It is calculated as

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.

Figure 14: Example

To calculate the SSE of the 10 pairs of values directly:


Enter in cell E23 the formula =sum((E12:E21 – C12:C21)^2) and press Ctrl+Shift+Enter. The formula
bar should show that cell E21 contains {=sum((E12:E21 – C12:C21)^2)}. The braces { } (which you
did NOT type) denote an array formula. Each value in the array of cells C12 to C21 is deducted from
the equivalent cell in the range E12 to E21 and the result is squared. All the resulting squared errors
are summed. Excel Help gives more information on using array formulae.
The Solver can then be used to minimise the value of SSE in cell E23 (objective cell) by adjusting the
values of A and B in cells B24 and B25. (It is not advisable to ask Solver to find the values of A and B
that make SSE equal to zero.)

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.

Recommended books are:

 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.

How to run MATLAB

You can start MATLAB the start menu. Click on All Programs  MATLAB 
MATLAB2015b
A window should pop up and start MATLAB.

To use MATLAB from home

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.

How to get help

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]

and for specific commands, e.g. :


>> help fft
[a help message on the fft function follows].

How to quit MATLAB

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

to the MATLAB prompt.

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.

We first look at the Command Window (with the >> prompt).

(i) Try the following arithmetical commands:

a) Type 2 + 3 and then press enter.

b) Now try: 5–4 2*3 1/2 2^5

c) How about: 0/1 1/0 0/0 ?

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

List of basic arithmetic operations in MATLAB include six operations

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)

(ii) How about algebra?

Type: a = 3 and press enter

a is a variable and we have assigned it the value of 3.

Now try: a = a + 2 and press enter

a = a * 10 and press enter

Do the results make sense?

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.

Now type: b = 3; press enter

Q1: What does the “;” do?

Answer: It means that nothing is printed to the screen – i.e. output is suppressed.

Check the value of b simply by typing

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!

c) Assign values to x and y, e.g.

x = 5
y = 3

Then assign x + y to another variable z, by

z = x + y

z =

What is the value of 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;

Keep this example in mind when we deal with loops!

(iii) MatLab has many special functions.

For example enter:


sqrt(pi) sin(pi/2) cos(pi*0.3) exp(2.5) log(10)
log10(10)

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 .

Q4: Use MATLAB to calculate

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.

Common choices are:

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

and thus try out all five format statements.

[For format short e, you should get


ans =
3.3333e-03]

When you use format short e or format long e, MATLAB writes out the numbers in
scientific notation.

i.e. 0.23e+000 = 0.23 × 100 = 0.23 × 1 = 0.23

0.23e+006 = 0.23 × 106 = 230000

0.23e-005 = 0.23 × 10–5 = 0.0000023

(The “e” means a power of 10 – it is nothing to do with e = 2.7 … !)

MatLab also uses this output for format compact for numbers that are large or small.

(iv) If things go wrong - Clear and clc

If you wish, you can clear the screen by typing clc.

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

The first element of “a” is 2


The second element of “a” is –5, etc.

Typing in the Command window


a(1)

gives the number in the first box

Typing in the Command window

a(2)

gives the number in the second box, etc.

Q6: What is a(3)? Print it out to check!

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

You could create these arrays as before, i.e.

x = [0, 1, 2, 3, 4, …];

y = [sin(0), sin(1), sin(2), sin(3), sin(4), …];

but this is very tedious, especially for long lists.

Fortunately MATLAB does this very easily. Thus simply type

x = 0 : 10;

Now enter x to see what it is (i.e. type x ).

Now type:

y = sin(x);
y =

Hopefully you will see that y(1) = sin ( x(1) )

26
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas

y(2) = sin ( x(2) )


y(3) = sin ( x(3) ), etc.

i.e. the y-array contains the corresponding sines of the x-array.

For a plot enter:


plot (x, y )

For a better plot you need more points. Enter

x = 0 : 0.1 :10 ;
y = sin(x);

(increments in x are now 0.l).

Now try:
plot (x, sin(x) ) , grid

(grid gives you a grid, surprisingly enough).

Suppose you wanted to plot y = x4, vs x. After entering

x = 0 : 0.1: 2 ;

You might think the obvious thing to do is to type

y = x ^4 ;
y

This clearly has not worked – you get an error message!

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

(. ^, .* ,. /)

Thus now try

y = x .^4 ;
y

Similarly if you wanted to plot: y = 2x2 – 3x +1 against x, you might type

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

If you wanted to plot: y = x sin(x) against x; you might type

x = -2: 0.1: 2;
y = x.*sin(x);
plot(x,y)

Q7: Plot the following functions against x in increments of 0.1:

i) y = cos(x) 0<x<2

ii) y = ln(x); 0<x<2

iii) y = e-2x; 0<x<3

iv) y =sin(x2); 0 < x < 2

v) y = tan(x)/x; 0.5 < x < 1

3. Writing MATLAB Programs

i) Using the editor

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.

Type in the following;

balance = 1000; % begin by initialising


variables
rate = 0.09;
interest = rate * balance; % calculate interest
balance = balance + interest; % calculate new interest
disp( ‘new balance:’ ); % print text
disp( balance) ; % print number

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.

c) Note the use of “;” to suppress unwanted output.

28
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas

d) The disp command prints things to the screen.

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.

Use the cursor to make any corrections.

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.

Make sure you understand how the program works!

Q8: What is the final balance? [1090]

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

balance = input(‘value of balance: ‘); % prompt to enter


initial balance
rate = input(‘value of rate: ‘); % prompt to enter
initial interest
interest = rate * balance; % calculate
interest
balance = balance + interest; % calculate new
interest
disp( ‘new balance:’ ); % print text
disp( balance) ; % print number

The number you type in when

value of balance:

appears on the screen is the number assigned to the variable balance. A similar thing happens
with the variable interest.

The program then goes on to calculate the new balance as before.

- Saving a program: script files -

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)

- Current directory and how to run a script -

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

C:\Documents and Settings\mjkssam6\My Documents\EC

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!).

Right click – select Run from the context menu.

To edit – select Open from the context menu.

N.B: MATLAB is case sensitive. X is different from x!

Do the following exercises, making sure you save the programs in My Documents and/or a
memory stick.

Q9: Write a program to convert temperatures in Celsius to temperatures in Fahrenheit

(Note: x oC = ( 9x/5 + 32) oF ), for an input temperature of your choice.

Q10: Write a program to solve the linear equation

a x + b = 0,

for a and b values of your choice.

Q11: Write a program to calculate the surface area and volume of a sphere ( 4r 2 and
4r 3 / 3 respectively), for an input value of r of your choice.

Q12: Write a program to solve the quadratic equation

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’

x’ is the column vector.

We now use this in the following program

1 2
Q13: Vertical motion under gravity (the equation to implement is s  ut  gt )
2

Type the following program in the editor.

% Vertical motion under gravity


g = 9.8; % acceleration due to gravity
u = 60; % initial velocity
t = 0 : 0.1: 12.3 ; % time values
s = u * t – g / 2*t .^2; % height

plot (t, s), title( ‘Vertical motion under gravity’ ) , …


xlabel ( ‘time’ ), ylabel ( ‘height’ ), grid

disp( [t’ s’] ) %display a table

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.

Note that in disp([t’ s’]) there is a space between t’ and s’ !

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

1) note that t is a row vector, containing equal increments of time values.

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.

3) Note the .^ arithmetic operator, used to square each element of t in turn.

4) a more sophisticated plot command that produces labels, titles, etc.

5) Note the use of column vectors to print out a table.

6) the ellipsis (…) joins the current line up with the following one.

Now do the following exercises, saving the programs.

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.

Q15: The concentration of a chemical, A, undergoing a first order chemical reaction,


varies with time as

[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.

Q16: Repeat the above for a second order chemical reaction, so

[ A]0
[ A] 
1  k[ A]0 t

32
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas

taking the same values for [A]0 and k.

More on graphics: plot vs fplot

MATLAB can produce graphical plots of series of data (using the command plot) or
functions (using the command fplot).

To plot from y-values, contained in a y-vector, against x-values, contained in an x-vector,


first set the values of the y and x vectors, e.g.

x =[1,2,3,4,5,6,7,8,9,10]
y =[1,4,9,16,25,36,49,64,81,100]

Then use the plot command

plot (x,y)

The plot is displayed in a new window.

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

You can also save the plot as a .bmp or .jpg image

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

or acting directly in the graph window.

fplot can also be used to plot functions of your choice

fplot ('4*x^3-2*x^2-200*x-50',[-10,10])

This command plots the polynomial 4x3-2x2-200x-50 in the interval -10≤ x ≤ 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]

Q18: Repeat the above for exp(  x 2 )  x

[Ans. 0.65]

More on plots: plotting two series of data together.

Often it is useful to plot several data in one single graph. The command plot of MATLAB
can do this easily.

Take for example the exercise Q14

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

4) Loops using for

Suppose you wanted to sum a series, e.g.

10000
1 1 1 1 1
 n  1  2  3   10000
n 1

You could do it like Q3, i.e.

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)

but this would be a very long program!

Please do not type this in – it will not work.

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!

We begin simply. On the command line type:

disp(‘Just going into the loop’);

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 output is:

Just going into the loop


In the loop. Iteration number:
1
In the loop. Iteration number:
2
In the loop. Iteration number:
3
In the loop. Iteration number:
4
In the loop. Iteration number:
5
Just exited from loop
final value of n
5

What is going on?

The loop begins with for n = 1:5 and finishes with end

The computer first sets n = 1. It writes

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

Just exited from loop


final value of n
5

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

(a) for n = 3:7


(b) for n = 1:3:10
(c) for n = 5:-1:1
(d) for n = 6:-2:1

In each case work out what the loop is doing.

Sequences and sums

Let us now sum some series. We begin with

n  1 2  3  4  5
n 1

We can do this by combining the for end construction with the program in Q3:

sum=0; %This must be set to zero


initially
for n = 1:5 % Loop over all n - values

sum = sum +n; % Add next term to the sum


disp([n,sum]); % displays n and sum within loop
end
disp(‘Just exited from loop’);
disp(‘final value of n and sum’ );
disp([n, sum]);

Note: make sure in MATLAB you use a single quotation mark in disp. The disp line should
look purple in the MATLAB editor!)

The print out is:

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.

Q20: Edit this program to calculate:

10
a)  n  1  2  3  4  5    9  10
n 1

[final value of n and sum

38
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas

10 55]

15

b)  n  5  6  7    14  15
n 5

[final value of n and sum


15 110]

10

c)  (3n)  3  6  9  27  30
n 1
(Do this using a for end loop, going up in steps of 3)

[final value of n and sum


30 165]

We can also do more complicated sums, e.g.

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

sum=0; %This must be set to zero


initially
for n = 1:10 % Loop over all n - values

sum = sum +1/n; % Add next term to the sum


disp([n,sum]); % displays n and sum within loop
end
disp(‘Just exited from loop’);
disp(‘final value of n and sum’ );
disp([n, sum]);

Ans: final value of n and sum


10.0000 2.9290

Q21: Edit this program to calculate:

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

n! n(n  1)(n  2) 3  2  1

fac=1; %This must be set to one initially


for n = 1:10 % Loop over all n - values
fac = fac*n; % Do the next multiplication in the
factorial
disp([n,fac]); % displays n and factorial so far
within loop
end
disp(‘final value of n and fac’ );
disp([n, fac]);

[Ans: final value of n and fac


10 3628800 ]

Q22: Edit this program to calculate:

15!! 1 3  5  7 1113 15

[Ans: final value of n and fac


15 2027025 ]

5) Making decisions with if

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:

< less than


<= less than or equal
== equal
~= not equal
> greater than
>= greater than or equal

Type the following on the command line

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

This will not work! Why?

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?

We can also write programs using this if-else-end facility.

Try the following:

r = rand % MATLAB random number between 0 and 1


if r < 0.5
disp ( 'move left' )
else
disp ( 'move right')
end

This is the basis for doing a random walk along a line.

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:

r = rand % Matlab random number between 0 and 1


if r < 0.25
disp ( 'move left' )
elseif r < 0.5

41
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas

disp ( 'move up')


elseif r < 0.75
disp ( 'move right')
else
disp ( 'move down')
end

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.

In this program calculate

disc = b^2 - 4*a*c;

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.

Firstly write a function program – fun.m – to calculate fun(x) = exp(-x) – x.

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”.

Test this on (a) x1 = 0 x2=1, (b) x1 = 1, x2=2, (c) x1=-1, x2 = 0.

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?

Here is a MATLAB program to do this.

42
Computational Methods for Chem. Eng. CHEN10050 A. Alfutimie/R. Villegas

a = 1000; % initial investment


r = 0.1; % rate of interest
bal = a;
year = 0;
disp( 'year balance' )

while bal < 2*a


bal = bal + r * bal;
year = year + 1;
disp( [year bal] )
end

The program keeps on advancing the years and adding on the interest until the statement bal
< 2*a is false, whereupon the loop ends.

Let us do another example.

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.

sum = 0.0; % Initialise the sum to zero


n = 0; % Initialise the counter in the sum to be
zero
disp('n sum')

while sum < 3


n = n+1; % Increment the counter
sum = sum + 1/n; %Accumulate the sum
disp( [n sum])
end

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.

(20 hours. Population is 1048576)

Ex. 15: Consider the series n


n 1
2
 1  2 2  32   Use the while-end construction to find

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

You have finished the handout! Congratulations!

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

You might also like