Title: Welcome to ENGGEN 131 Engineering Computation and Software Development
1Welcome to ENGGEN 131Engineering Computation and
Software Development
Module 4 Differential Equations Function
Functions Strings
2Design Problem
- Many chemical reactions are exothermic i.e.
they release heat as they proceed. - You are designing a chemical reactor in which
chemical A is converted into chemical B. - As part of the design you need to know the
concentration of chemical A and the temperature
of the reactor as a function of time. - Posted online by Darin Ridgway, Department of
Chemical Engineering, Ohio University
(http//webche.ent.ohiou.edu/matlab/)
3Mathematical Model
- The behaviour of the chemical reactor can be
described by two ordinary differential equations
(ODEs)
C(t) concentration of A T(t) temperature t
time h, k, E, R constants
45 Steps for Problem Solving
- State the problem clearly
- Describe the input and output information
- Work the problem by hand (or with a calculator)
for a simple set of data - Develop a solution and convert it to a computer
program - Test the solution with a variety of data
52. Describe the input and output information
- Inputs
- constants h, k, E, and R describing the rate of
change of concentration of chemical A and the
temperature - initial concentration of chemical A and initial
temperature - final time at which prediction is required,
tfinal - Ouputs
- - concentration of chemical A, C and temperature,
T as a function of time, t
63. Work the problem by hand
- The coupling between concentration and
temperature makes these equations difficult to
integrate analytically. - Could solve using a version Euler's method but
we'll skip that since this is not a mathematics
course!
74. Develop a solution and convert it to a
computer program
- Matlab has numerical methods to solve systems of
differential equations implemented as part of its
toolbox. - The Matlab tools are set up to solve a generic
system of equations.
two variables
two ODEs
8Reactor Example
- The table below shows the correspondence between
the variables and functions in the generic
system of ODEs and our reactor problem.
y1
y2
t
f1 (rate of change of C)
f2 (rate of change of T)
9Developing a Matlab Solution
- We will use a Matlab function called ode45 to
solve the system of ODEs representing the
chemical reactor. - T,Y ODE45(ODEFUN,TSPAN,Y0)
- where TSPAN T0 TFINAL
- Y0 Y10 Y20
user defined Matlab function evaluating f1 and f2
10Matlab Implementation Lecture version)
- Well start by writing the function defining the
right hand side (RHS) of the ODEs.
Function takes inputs of a time value (t) and an
array (y) which holds the concentration and
temperature at that time.
function f reactorfunc(t,y)
Comments important!
set up constants
Define constants in reactor equations.
E 2500 the activation energy in J/mol
R 8.314 the gas constant in J/(mol K)
k - 0.1 constant in s-1
h -10 constant in (K L)/mol
work out RHS of ODEs
store in an array to be returned
Calculate RHS values. y(1) is concentration. y(2)
is temperature.
f(1) ky(1)exp(-E/R/y(2))
f(2) hky(1)exp(-E/R/y(2)) f f' return
Filename reactorfunc.m
11Matlab Implementation
- Well start by writing the function defining the
right hand side (RHS) of the ODEs.
Function takes inputs of a time value (t) and an
array (y) which holds the concentration and
temperature at that time.
function f reactorfunc(t,y)
set up constants
E 2500 the activation energy in J/mol
R 8.314 the gas constant in J/(mol K)
k - 0.1 constant in s-1
h -10 constant in (K L)/mol
work out RHS of ODEs
store in an array to be returned
Calculate RHS values. y(1) is concentration. y(2)
is temperature.
f(1) ky(1)exp(-E/R/y(2))
f(2) hky(1)exp(-E/R/y(2)) return
Filename reactorfunc.m
12Matlab Implementation
- Now well write a main script file to call ode45.
Filename reactor.m
set up initial conditions Y0(1) 1.0
initial concentration of chemical A Y0(2)
300.0 initial temperature in Kelvin set
up time range tspan(1) 0.0 start
time, s tspan(2) 150.0 end time, s
call ODE solver t,y ode45(_at_reactorfunc,
tspan, Y0)
13_at_reactorfunc ?
_at_ symbol means the function input is another
function, not a variable.
14Results
- When the reactor.m script file is run it outputs
two arrays
t 0 1.3688 2.7376 4.1063
5.4751 9.2251 12.9751 16.7251
y 1.0000 300.0000 0.9510 300.4904
0.9043 300.9574 0.8598 301.4022 0.8174
301.8256 0.7115 302.8846 0.6191
303.8092 0.5385 304.6155
concentration of A
reactor temperature
15Results
plot concentration versus time plot(t,y(,1)) xl
abel('Time, s') ylabel('Concentration of chemical
A') title('Concentration of A in batch
reactor') figure plot temperature versus
time plot(t,y(,2)) xlabel('Time,
s') ylabel('Temperature, K') title('Temperature
in batch reactor')
16Results
175. Test the solution with a variety of data
- If the rate constant k is increased the reaction
should proceed faster
k -0.5
k -0.1
18Function functions
- ode45 is an example of a function function,
i.e. a function which takes another function as
an input. - If you are going to write your own function
functions you will need to use the feval command
to evaluate the function supplied as an input.
19Electrical Engineering Example
- Voltage in an electrical circuit often varies
with time. It is often convenient for electric
engineers to define an average voltage. The
average which is typically used is root mean
square voltage (or RMS voltage).
20RMS Voltage
- Will we assume V(t) is such that the integral can
not be done analytically. - Will we do a simple numerical integration using
the midpoint rule.
f(t)
0
T
t
211. State the Problem Clearly
- For any function V(t) calculate the RMS voltage
which occurs over a time interval, T. - 2. Describe the input and output information
- Inputs
- V(t) function, which takes t as an input and
calculate V as an output - T, time interval to calculate RMS voltage over
- Outputs
- - Root mean square voltage of V(t) over time
interval T.
223. Work the Problem by Hand
Exact solution
233. Work the Problem by Hand
- Use 4 panels to integrate from t0 to t8,
therefore dt2, T8.
244. Develop a solution and convert it to a
computer program
function RMS RMSVoltage(voltage,T,n) dt
T/n calculate dt by dividing total time
b by number of panels t
linspace(0dt/2.0,T-dt/2.0,n) define points
in time to evaluate voltage Vt
feval(voltage,t) evaluate the function
voltage function at each point in
time VtSquared Vt.Vt square voltage
values (note dot operator) RMS
sum(VtSquared)dt area of each panel equals
VtSquared times dt, sum these areas RMS
sqrt(1.0/TRMS) finally divide by T and
take square root to calculate
RMS return
Filename RMSVoltage.m
25Matlab Implementation
- We can use our Matlab function to calculate the
RMS voltage of any voltage we supply. - For example
user supplied function
function V voltageExample(t) V
sqrt(t) return
usage from Matlab command line (time 8s, n4
panels)
Filename voltageExample.m
gtgt RMSVoltage(_at_voltageExample,8,4)
26Eval Command
- The final command we will introduce today is
eval. - This command takes a string as an input and
evaluates it as if it were a Matlab command, for
example
I1 1 0 0 0 1 0 0
0 1 I2 2 0 0 0 2
0 0 0 2 I3 3 0 0
0 3 0 0 0 3
for i13 eval('I',num2str(i),'eye(3)',num2s
tr(i)) end
27Finding the Roots of a Function
- Matlabs fzero function is a useful tool to find
the roots of a function, i.e. given a function
f(x) what value of x gives f(x)0. - The function can be a user-defined function.
- The syntax for fzero is
x fzero(fun,x0)
root
function
initial guess of the root
28Example Million Bank Balance!
- Assume you have 50,000 in the bank and you want
to leave it the bank earning interest until you
have 1,000,000. - What rate of interest is required if you aim to
reach your target in 20 years? - Your bank balance will grow according to
29Example Million Bank Balance!
- You could actually solve this problem using
skills with logs from MM1, but here we will use
fzero. - First define a function which calculates how far
from your target you are for a given interest
rate.
function deficit deficit_dollars(rate)
deficit 1000000 - 50000(1rate/100)20 end
30Example Million Bank Balance!
- Now call fzero using
- Here we are using 12 interest as an initial
guess of what the answer will be. The actual
answer is 16.2.
rate_required fzero(_at_deficit_dollars,12)
31What are strings?
- So far variables have contained numbers
- Scalars, vectors, matrices
- Image matrices (m x n x 3) represent colour
intensities - Another very useful type of data is a character
- Matlab uses Unicode
- A 16-bit character encoding scheme allowing
characters from Western European, Eastern
European, Cyrillic, Greek, Arabic, Hebrew,
Chinese, Japanese, Korean, Thai, Urdu, Hindi and
all other major world languages, living and dead,
to be encoded in a single character set. - www.polyphonic-ringtones-ring-tones.co.uk/gl
ossary.html - Array of characters string
- Matlab uses row arrays of characters
32String Variables
- String variables are named just like numerical
variables - Assigned using other string variables or string
constants - String constant characters between ' and '
- Useful for preloading strings
- Input commands to the user
- Messages for display
- Plot titles, etc
- Searching string data often useful
- Looking up text information
33Example Creating Strings
34Strings as Arrays
- Matlab string is a row array (1 n)
- May use many existing array operations
35Other Operations on Strings
- Can use to obtain subranges
- within a string
- substrings
- Can concatenate
- strings together
36Comparing Strings
- Two strings equal if they contain exactly
identical characters in each position - including blanks
- Compare strcmp
- Compare first n positions strncmp
- Compare ignoring case strcmpi
37Example Comparing Strings
38Upper and Lower Case
- Strings are case-sensitive
- 'a' is not equal to 'A'
- Can convert a string to all upper case or all
lower case - Useful when comparing a user input
- Allows user to type in either case
39The strfind Function
Engineering Science Dept
40Converting Numeric to String
41Multiple Strings
- Could put multiple strings into rows of a matrix
- We have done this with numbers
- Points for the getlength example
- Rows must be same length!
- Could pad rows with spaces
- Better to treat strings like other types
- Integers, doubles, etc
- Matrix of integers has one integer for each
element - Matrix of strings has different number of
characters (one string) for each element - Matlab gives us cell arrays
42Creating Cell Arrays
- Same as creating an array, use instead of
2D array of strings
43Accessing Cell Arrays
- Using ( )
- gives cell array
- Using
- gives string
44Accessing Cell Arrays
45Example Encryption
- We want to use MATLAB to implement a basic
substitution encryption - Here is a shift right substitution
- a b c d e f g h i j k l m n o p q r s t u v w x y
z - b c d e f g h i j k l m n o p q r s t u v w x y z
a - I am Mike becomes J bn Njlf
- We are given the encryption as 2 strings
- Characters to encrypt
- Represents the substitution
- Write a program to encrypt and decrypt
465 Steps for Problem Solving
- State the problem clearly
- Given an encryption, be able to encrypt and
decrypt messages. - Describe the input and output information
- Work the problem by hand (or with a calculator)
for a simple set of data - a b c d e f g h i j k l m n o p q r s t u v w x y
z - b c d e f g h i j k l m n o p q r s t u v w x y z
a - I am Mike becomes J bn Njlf
Encryption strings
Message
Encrypted/decrypted message
Encrypt/decrypt option
475 Steps for Problem Solving
- Develop a solution and convert it to a computer
program - Pseudocode
- Initialise the encryption
- Get the message to encrypt/decrypt
- If the message is to be encrypted
- Encrypt the message
- Else
- Decrypt the message
- Return the resulting message
48Need to implement these!
49Need to implement these!
50Encrypt
- State the problem clearly
- Encrypt a message using an encryption
- Describe the input and output information
- Work the problem by hand (or with a calculator)
for a simple set of data - a b c d e f g h i j k l m n o p q r s t u v w x y
z - b c d e f g h i j k l m n o p q r s t u v w x y z
a - I am Mike becomes J bn Njlf
- Develop a solution and convert it to a computer
program - Pseudocode
- for each character in the message
- Find its position in the characters to encrypt
- if it exists
- Replace it with the substitute character
- Return the resulting message
Encryption
Encrypted message
Message
51encrypt.m
- Show via MATLAB editor
- Print as a single file in course manual
52Test the solution with a variety of data
53decrypt similar to encrypt
54Test the solution with a variety of data
- Testing the main algorithm
55Example On-the-fly Search of an Address Book
- We want to implement an on-the-fly search of an
address book - As characters are entered only names (
information) that match are displayed - Jason Wong 29 Bellview Road, Epping
- Emily Marsh 8a Paramount Drive, Glenbonnie
- Emma Wondhalla 92 The Strand, West Norwich
- Tak Marshall 105 Royal Crescent, Olivertown
- If e is entered, then m
- Emily Marsh 8a Paramount Drive, Glenbonnie
- Emma Wondhalla 92 The Strand, West Norwich
- then i
- Emily Marsh 8a Paramount Drive, Glenbonnie
565 Steps for Problem Solving
- State the problem clearly
- Given an address book and a sequence of
characters - Describe the input and output information
- Work the problem by hand (or with a calculator)
for a simple set of data - No characters
- Jason Wong 29 Bellview Road, Epping
- Emily Marsh 8a Paramount Drive, Glenbonnie
- Emma Wondhalla 92 The Strand, West Norwich
- Tak Marshall 105 Royal Crescent, Olivertown
- e then em
- Emily Marsh 8a Paramount Drive, Glenbonnie
- Emma Wondhalla 92 The Strand, West Norwich
- then emi
- Emily Marsh 8a Paramount Drive, Glenbonnie
Address Book
Matching information
Characters
57Develop a solution and convert it to a computer
program
- Pseudocode
- partialName is empty
- stillTyping true
- while stillTyping
- Get the next character
- Add it to partialName
- for i 1 to lines in book
- if partialName matches ith name
- display ith information
- if name found
- stillTyping false
58- One page file
- searching requires a cell array book with a
list - of names to search in the first column
-
- if iscell(book) size(book, 2) lt 1,
- error('book must be a cell array with at
least 1 column') - end
-
- partialName is empty
- partial
- stillTyping true
- stillTyping true
- while stillTyping
- while stillTyping,
- Get the next character
- reply input('Enter next character gt ',
partial, 's') - if length(reply) 1,
- error('You must enter a single
character') - end
59Test the solution with a variety of data
60Optional Reading
- Introduction to Matlab 7 for Engineers,
William J. Palm III - page 37
- pages 209-210
- page 240
- pages 452 455