Matlab Practical: Solving Differential Equations



Similar documents
Solving ODEs in Matlab. BP205 M.Tremont

The Kinetics of Enzyme Reactions

Numerical Methods for Differential Equations

Numerical Solution of Differential Equations

Curve Fitting and Parameter Estimation

To get started, type one of these: helpwin, helpdesk, or demo. For product information, type tour or visit

Nonlinear Algebraic Equations. Lectures INF2320 p. 1/88

Mechanics 1: Conservation of Energy and Momentum

Numerical Methods in MATLAB

How long is the vector? >> length(x) >> d=size(x) % What are the entries in the matrix d?

Euler s Method and Functions

Solutions to Practice Problems for Test 4

Modeling with Python

2.2 Derivative as a Function

the points are called control points approximating curve

Curve Fitting, Loglog Plots, and Semilog Plots 1

Section 3.7. Rolle s Theorem and the Mean Value Theorem. Difference Equations to Differential Equations

LAB TOPIC 4: ENZYMES. Enzyme catalyzed reactions can be expressed in the following way:

0 Introduction to Data Analysis Using an Excel Spreadsheet

Cooling and Euler's Method

A Brief Review of Elementary Ordinary Differential Equations

x 2 + y 2 = 1 y 1 = x 2 + 2x y = x 2 + 2x + 1

PSTricks. pst-ode. A PSTricks package for solving initial value problems for sets of Ordinary Differential Equations (ODE), v0.7.

Microeconomic Theory: Basic Math Concepts

Numerical Solution of Differential

Chemical Kinetics. 2. Using the kinetics of a given reaction a possible reaction mechanism

Calibration and Linear Regression Analysis: A Self-Guided Tutorial

6 Scalar, Stochastic, Discrete Dynamic Systems

Lecture 11 Enzymes: Kinetics

5 Correlation and Data Exploration

Classroom Tips and Techniques: The Student Precalculus Package - Commands and Tutors. Content of the Precalculus Subpackage

MATLAB Programming. Problem 1: Sequential

Visualizing Differential Equations Slope Fields. by Lin McMullin

Problem Set 6 Question 1

Derive 5: The Easiest... Just Got Better!

Nonlinear Algebraic Equations Example

1 Error in Euler s Method

Department of Chemical Engineering ChE-101: Approaches to Chemical Engineering Problem Solving MATLAB Tutorial VI

Beginner s Matlab Tutorial

Scalar Valued Functions of Several Variables; the Gradient Vector

Lab 4.4 Secret Messages: Indexing, Arrays, and Iteration

Quick Tour of Mathcad and Examples

Lab 1. The Fourier Transform

Plot and Solve Equations

PRACTICE FINAL. Problem 1. Find the dimensions of the isosceles triangle with largest area that can be inscribed in a circle of radius 10cm.

8.2 Elastic Strain Energy

Review of Fundamental Mathematics

1 Finite difference example: 1D implicit heat equation

Continued Fractions and the Euclidean Algorithm

INTRODUCTION (Syllabus, Numerical Methods & Computational Tools)

Enzyme Action: Testing Catalase Activity 50 Points

1 Description of The Simpletron

3.2 Sources, Sinks, Saddles, and Spirals

AMATH 352 Lecture 3 MATLAB Tutorial Starting MATLAB Entering Variables

1 Review of Least Squares Solutions to Overdetermined Systems

In order to describe motion you need to describe the following properties.

November 16, Interpolation, Extrapolation & Polynomial Approximation

To give it a definition, an implicit function of x and y is simply any relationship that takes the form:

CD-ROM Appendix E: Matlab

*X100/12/02* X100/12/02. MATHEMATICS HIGHER Paper 1 (Non-calculator) MONDAY, 21 MAY 1.00 PM 2.30 PM NATIONAL QUALIFICATIONS 2012

How To Understand Enzyme Kinetics

Lecture Notes to Accompany. Scientific Computing An Introductory Survey. by Michael T. Heath. Chapter 10

What does the number m in y = mx + b measure? To find out, suppose (x 1, y 1 ) and (x 2, y 2 ) are two points on the graph of y = mx + b.

PGR Computing Programming Skills

Lecture 2 Mathcad Basics

Student Performance Q&A:

3. Reaction Diffusion Equations Consider the following ODE model for population growth

Chapter 4 One Dimensional Kinematics

The Fourth International DERIVE-TI92/89 Conference Liverpool, U.K., July Derive 5: The Easiest... Just Got Better!

Lecture 1: Systems of Linear Equations

MATLAB Basics MATLAB numbers and numeric formats

5.1 Radical Notation and Rational Exponents

Numerical Methods in MATLAB

Solutions to Homework 10

Homogeneous systems of algebraic equations. A homogeneous (ho-mo-geen -ius) system of linear algebraic equations is one in which

This unit will lay the groundwork for later units where the students will extend this knowledge to quadratic and exponential functions.

Integer Factorization using the Quadratic Sieve

General Framework for an Iterative Solution of Ax b. Jacobi s Method

MATLAB and Big Data: Illustrative Example

Lecture 3: DC Analysis of Diode Circuits.

Lines & Planes. Packages: linalg, plots. Commands: evalm, spacecurve, plot3d, display, solve, implicitplot, dotprod, seq, implicitplot3d.

1 Solving LPs: The Simplex Algorithm of George Dantzig

Chapter 6 Work and Energy

Introduction to functions and models: LOGISTIC GROWTH MODELS

Guide to Using the Ti-nspire for Methods - The simple and the overcomplicated Version 1.5

TI-83/84 Plus Graphing Calculator Worksheet #2

Pre-Algebra Lecture 6

F.IF.7b: Graph Root, Piecewise, Step, & Absolute Value Functions

Math Numerical Analysis Homework #2 Solutions

6.1. The Exponential Function. Introduction. Prerequisites. Learning Outcomes. Learning Style

Techniques of Integration

Temperature Scales. The metric system that we are now using includes a unit that is specific for the representation of measured temperatures.

Separable First Order Differential Equations

OPTIMAL CONTROL OF A COMMERCIAL LOAN REPAYMENT PLAN. E.V. Grigorieva. E.N. Khailov

Numerical Analysis Lecture Notes

Using Microsoft Excel to Plot and Analyze Kinetic Data

Nonlinear Programming Methods.S2 Quadratic Programming

Linear Programming. March 14, 2014

Transcription:

Matlab Practical: Solving Differential Equations Introduction This practical is about solving differential equations numerically, an important skill. Initially you will code Euler s method (to get some more practice with simple Matlab programming), but we will soon move on to using the built-in functions for solving differential equations, as these built-in functions are invariably used in practice. By the end of the practical you should be able to get Matlab to solve coupled nonlinear systems of differential equations of the type that often arises in modelling studies. In particular we will investigate the equations governing enzyme kinetics. The first part of this practical concerns the differential equation dy ty subject to y(0) 2 (1) Again the practical consists of a series of exercises for you to do: these are boxed. Before each exercise, any necessary Matlab commands and concepts are briefly introduced; anything that should be typed into Matlab is denoted by courier. As you are actually typing the Matlab commands, think about why they behave as they do; if at any time you do not understand then please ask. Euler s method As discussed in the lecture, Euler s method is the simplest way of solving differential equations numerically. The method relates the current value of the right hand side of a first order differential equation to the new value of the numerical approximation. In particular, in solving the first order differential equation dy f ( y, t) subject to the initial condition y(0) = y 0, Euler s method creates a sequence of values y n, where y y( n t) for n > 0. The value y n is an approximation to the value of the n solution y at t = n t, where t is the step length. A single step of Euler s method follows the rule y n 1 y n ( t) f ( yn, n t) Exercise One Use Matlab to solve Equation (1) using Euler s method with time steps t = 0.01, up to maximum time T max = 3. Plot your approximate solution. (Hint: one way of doing this would be to work out in advance how many steps are required, and then to use a for loop to automate the calculation of y n+1 from y n and n t, storing the values of y and t in vectors [for later plotting]).

As you may have realised, it is in fact relatively easy to solve Equation (1) using a pen and paper. Exercise Two Solve Equation (1) analytically (Hint: this differential equation can be solved using separation of variables) Exercise Three Create a new function exactsoln(t), which finds the value of the exact solution you found in Exercise Two. Make sure it works with both scalar and vector inputs t. Now we have an explicit form for the solution, a useful thing to do would be to plot it and compare with the numerical solution via Euler s method. To date you have plotted all graphs on separate axes. However a natural goal is often to plot two curves on the same axes. Consider the following (again type it in line by line so you can see what is happening). x = [0:0.01:6*pi]; y = sin(x); z = cos(x); plot(x,y); plot(x,z, r ); hold on; plot(x,y); xlabel( x ) ylabel( y ) By issuing the commands help hold investigate what is going on. Exercise Four Plot the exact solution and your numerical approximation according to Euler s method on the same axes. By investigating the results of help print, work out how to save the figure to a file in jpeg format. Using built in Matlab functions for solving differential equations Euler s method is impractical for solving differential equations, since very small steps are required to achieve satisfactory accuracy. Instead Matlab provides a number of built-in functions for solving differential equations; the workhorse is ode45 (technically this is a fourth order Runge-Kutta method with fifth order error control ; the basic idea is similar to Euler s method, but a more sophisticated approximation is

used to find the slope of the tangent, and by default the method chooses the sizes of its individual steps to ensure satisfactory accuracy). According to the Matlab help, ode45 is what you should try first, and it is all that will be required in this practical. The easiest way of using the built-in differential equation solvers relies on the right hand side of the differential equation being specified in an appropriate function. Exercise Five Create a function myrhs(t,y) which returns the right hand side of Equation (1) (i.e. given a value of t and y, returns their product). It does not need to be vectorised; i.e. it is sufficient to write a function which expects only scalar input arguments, and which returns a single value. The basic syntax for the built-in solvers follows ode45(<function>,<domain>,<initcond>) where <function>, <domain> and <initcond> are specified by the user. In particular, try the following trange = [0,1]; yzero = 1; [myt,myy]=ode45(@myrhs,trange,yzero); % solve plot(myt,myy, c ); % plot Exercise Six By altering the above code, produce a plot of the solution of Equation (1) using ode45 over the range t=0 3 and with y(0) = 2. By plotting the exact solution you created in Exercise 3 on the same axes, test the quality of the numerical approximation. (Hint: you may wish to request that Matlab plots one of the graphs using a symbol such as o, as otherwise the graphs may be so close that one covers the other). Examine the contents of the vector myt and check the number of elements it contains using length(). Note that in approximating the solution, Matlab has selected a particular partition of the range specified, and returned the values of y and t at those points. Often is it desired that the user specifies these values (e.g. when they are to be used in some further calculation). Check you understand the following (note the definition of trange is different) trange = [0:0.01:1]; yzero = 1; [myt,myy]=ode45(@myrhs,trange,yzero); % solve plot(myt,myy, c ); % plot

It is important to point out here that Matlab continues to use the same partition of values internally; the only thing that changes is the values of t for which it returns the solution Solving coupled differential equations The solvers in Matlab work as you would expect for coupled differential equations; the important thing to remember here is that the function corresponding to the right hand side system must now return a (column) vector. Consider the following system (which may be familiar to you as the simplest version of the Lotka-Volterra equations for a predator P and its prey V) dv 0.1V 0.2VP dp 0.4PV 0.2P The following function implements the right hand side of these equations, taking some care to ensure that the return value is a column vector function ret=lvrhs(t,y) % set up ret in correct form (i.e. a column vector) ret = zeros(2,1); % extract current values of V and P V = y(1); P = y(2); % return updates ret(1) = 0.1 * V - 0.2 * V * P; ret(2) = 0.4 * P * V - 0.2 * P; Type this into a file called lvrhs.m and save it. Then enter the following code at the command line trange = [0,10]; yzero = [0.2,1.1]; [myt,myy]=ode45(@lvrhs,trange,yzero); % solve plot(myt,myy(:,1),'c'); hold on plot(myt,myy(:,2)); legend('prey','predator'); xlabel( t ); ylabel( population densities ); The time evolution of predator and prey is displayed, showing the characteristic cycles.

Chemical kinetics As you probably know, enzymes are proteins that catalyse a biochemical reaction by reducing the activation energy required for the reaction to proceed. They are often specific to a particular substrate, and catalyse its conversion to a product, themselves remaining unchanged by the reaction. In the simplest and archetypal situation, Michaelis-Menten kinetics, they accomplish this in two steps, first forming a complex with the substrate, which then breaks down to form the product and recover the enzyme k1 k2 S E C P E k 1 where we are assuming the back-reaction (i.e. from P + E -> C) is so slow as to be negligible. The constants k1, k-1 and k2 are the rate constants governing the speeds of the individual reaction steps (note that the first reaction is assumed to be reversible). The equations governing the kinetics follow ds k C k SE 1 1 de ( k 1 k2) C k1se dc k SE ( k k ) C dp kc 2 1 1 2 Exercise Seven Confirm that the total amount of enzyme is conserved (i.e. E + C = E 0, where E 0 is the amount of enzyme present initially). Also confirm that, since substrate can only occur in its original form, bound to the enzyme or converted to the product, that S + C + P = S 0, where S 0 is the amount of substrate present initially. (2) The manipulations performed above mean that the four dimensional system can in fact be rewritten as the pair of coupled equations ds k 1C k1s ( E0 C) dc (3) k S 1 ( E C 0 ) ( k k 1 2) C The values of E and P can be determined via E E C 0 P S S C 0 (4) Exercise Eight Write Matlab code to solve the system in Equation (3), and plot the amount of substrate and complex against time for k 1 = 5 M -1 s -1, k -1 = 0.1 s -1, k 2 = 1 s -1, with S 0 = 5 M, E 0 = 0.1 M, until T m = 20 (seconds).

Exercises for more advanced programmers Solving higher order equations (optional) The numerical routines we have discussed so far are restricted to first order systems (i.e. where the highest derivative in any equation is the first derivative, e.g. dy/). However, on occasion higher order equations occur; simple second order equations were covered in the lecture. In order to solve these, some trickery is required. Consider the second order differential Equation 2 d Y dy t dy Y e Y 2 25 59 5 6 subject to (0), (0) (5) 12 60 Exercise Nine Find the exact solution of Equation (5) Exercise Ten By introducing the derived variable Z=dY/, show how the second order Equation (5) can be transformed to a pair of coupled first order equations for dy/ and dz/. Exercise Eleven Solve the equations using Matlab and compare the solution for Y with that according to the exact solution. Options to ode45 (optional) A number of options can be passed to ode45. Two that can sometimes be important are the relative and absolute tolerances, RelTol and AbsTol, respectively. Internally, at each step of the algorithm the routine generates an approximation to the error during that step.. If y k is the approximation at step k, and e k is the approximate error at this step, then MATLAB chooses its partition to ensure e k max(reltol yk, AbsTol), where the default values are RelTol = 0.001 and AbsTol = 0.000001. The following code changes AbsTol, and shows how options can be passed to ode45 (in case you need to control these errors in the future, or indeed want to ever pass other options to these commands). options=odeset( RelTol,1e-10); trange = [0:1]; yzero = 1; [myt,myy]=ode45(@myrhs,trange,yzero,options); % solve Nik Cunniffe