matlab tutorial basic

143
EG–399 Engineering Analysis III K. Morgan Civil & Computational Engineering Centre School of Engineering University of Wales Swansea Second Teaching Block 2006–2007

Upload: halimsha

Post on 21-Sep-2014

6.567 views

Category:

Documents


3 download

DESCRIPTION

Swansea University lecture notes

TRANSCRIPT

Page 1: MATLAB TUTORIAL BASIC

EG–399Engineering Analysis III

K. MorganCivil & Computational Engineering Centre

School of EngineeringUniversity of Wales Swansea

Second Teaching Block2006–2007

Page 2: MATLAB TUTORIAL BASIC

General Module Information

Lectures & Computer Laboratory Classes

There are slots for formal lectures and computer laboratory classes allocated to this module in the

timetable. Not all slots will be used every week.

Module Objectives

This module aims to develop your problem solving ability. This will be achieved by illustrating

(a) how the modelling of engineering systems frequently results in the requirement to solve an

ordinary or partial differential equation;

(b) how MATLAB may be used to produce a solution of the model equation.

1

Page 3: MATLAB TUTORIAL BASIC

General Module Information

What is MATLAB?

MATLAB (MATrix LABoratory) is a software package for interactive numerical computation, graph-

ics and data analyis. It provides engineers with a versatile platform for solving a wide range of

computational problems.

General advantages of MATLAB over other packages include:

1. greater efficiency for problems involving matrices;

2. a wider range of intrinsic functions and toolboxes are supported;

3. greater versatility for problems involving loops and decisions;

4. better graphics.

Availability of MATLAB

MATLAB may be accessed under your account on the School of Engineering PC network by follow-

ing the path start→programs→maths→MATLAB

2

Page 4: MATLAB TUTORIAL BASIC

General Module Information

MATLAB and this Module

We will use the capabilities of MATLAB to solve ordinary and partial differential equations:

1. obtaining exact analytical solutions of ordinary differential equations when this is possible;

2. obtaining approximate numerical solutions otherwise.

Module Texts

These notes, together with the additional information provided in the lectures and the laboratory

classes, should serve as your basic source of information for this module.

Further information on modelling with differential equations, can be obtained from any modern

text book on advanced engineering mathematics, such as Advanced Engineering Mathematics,

E. Kreyszig, John Wiley & Sons Inc, (ISBN 0471553808), 1993, TA330 KRE7

Further information on the use of MATLAB to solve ordinary differential equations can be found in

any of the many text books that describe the use of MATLAB e.g.

MATLAB Student Version, Mathworks Ltd, (ISBN 0967219566), 2003

3

Page 5: MATLAB TUTORIAL BASIC

General Module Information

Module Texts (continued)

Numerical Methods Using MATLAB, J. E. T. Penny & G. Lindfield, Prentice Hall, (ISBN 0130126411),

2000, QA297 LIN2

Mastering MATLAB 6, D. C. Hanselman & B. C. Littlefield, Prentice Hall, (ISBN 0130194689), 2000,

TA45.5 M17HAN

MATLAB 6 for Engineers, A. Biran & M. Breiner, Prentice Hall, (ISBN 0130336319), 2002, TA345.5 M17BIR3

A detailed guide to the MATLAB toolbox that enables the solution of certain partial differential equa-

tions can be found in the file toolboxguide.pdf that may be copied from drive G on the School of

Engineering PC network, following the path MATLAB→work→EG399.

MATLAB Resources on the Internet

You can also learn more about MATLAB by making use of the large amount of information that is

available on the Internet, e.g.

1. the MathWorks are the developers of MATLAB and their Web site at

http://www.mathworks.com/

provides details of new products, related books and user supplied files;

4

Page 6: MATLAB TUTORIAL BASIC

General Module Information

MATLAB Resources on the Internet (continued)

2. for links to a wide range of MATLAB educational sites, look at

http://www.eecemaine.edu/mm/matweb.html

3. you should review your basic knowledge of MATLAB by looking again at the notes you were given

last year; introductory notes can also be found at the following sites:

http://www.maths.dundee.ac.uk/~ftp/na-reports/MatlabNotes.pdf

http://www.maths.uq.edu.au/~gac/mlb/mlb.html

http://www.math.mtu.edu/~msgocken/intro/intro.html

MATLAB On–Line Help

Remember that MATLAB has its own built–in extensive on–line help facility that can also be used to

provide information on the use of MATLAB.

5

Page 7: MATLAB TUTORIAL BASIC

General Module Information

Assessment

The assessment for this module will be based solely upon submitted work and there will be no formal

examination. You will be asked to submit for marking your solutions to 3 prescribed assignments.

The first assignment will not involve the use of MATLAB and will be worth 20 marks. To complete

the second and third assignments, you will be required to use MATLAB m–files. These assignments

will each be worth 40 marks.

Marking the MATLAB Assignments

For the MATLAB assigments, marks will be awarded for

1. the quality of the submitted work (40%);

2. the accuracy of the results produced (50%);

3. the MATLAB techniques employed (10%);

Failure to attend Laboratory Classes will normally result in the deduction of 5 marks for each Class

missed.

6

Page 8: MATLAB TUTORIAL BASIC

General Module Information

Assignment Submission Details

Solutions to the assignments should be submitted in hard copy form only.

The individual assignments must be submitted, at a prescribed lecture, as follows:

Assignment Week Number Date

1 18 26 Feb–02 Mar

2 22 23 Apr–27Apr

3 24 07 May–11 May

Assignments that are submitted late will normally be awarded zero marks.

Late submissions due to certificated illness will be dealt with according to standard procedures.

Advice on the procedure to be followed when submitting assignments will be given later.

7

Page 9: MATLAB TUTORIAL BASIC

General Module Information

Academic Honesty

Read the sections on unfair practice and plagiarism in the School of Engineering Handbook and in

the University Handbook.

Students are encouraged to work together on the module problems and to study in groups to help

each other learn the material.

However, you are expected to submit for marking only work that represents your own efforts.

Note that simply changing the variable names in a MATLAB file will not be sufficient to hide the fact

that two solutions are essentially the same.

Programming style tends to be very individualistic: similarities in style and formatting will always be

apparent, even if superficial changes are made.

Consider this carefully before giving your work to a colleague to ‘help them out’.

Submitted assignments must contain a statement confirming that the work submitted is yours alone.

8

Page 10: MATLAB TUTORIAL BASIC

General Module Information

Advice on MATLAB

1. Improving your MATLAB technique will only be possible if you work at your general knowledge

of MATLAB;

2. Spend some extra time early in this Teaching Block to recall the basic format of MATLAB;

3. Complete the problems promptly and don’t leave the assignments until the last minute;

4. Most of the concepts introduced in this module are not difficult, but you will require to spend

time to produce the solutions to the assignments;

5. Use the library, the on–line MATLAB help facility and Internet based resources to provide you

with additional information.

9

Page 11: MATLAB TUTORIAL BASIC

Ordinary Differential Equations

Basic Definitions

Consider a typical differential equation

dy

dt+ αy = f(t)

where α is a constant.

Here t is the independent variable and y(t) is the dependent variable.

An equation of this type, which includes derivatives of a dependent variable with respect to a single

independent variable, is an ordinary differential equation.

The order of a differential equation is given by the order of the highest derivative in the equation, so

this is a first order equation.

An equation in which the dependent variable and its derivatives appear in a linear fashion is called

a linear differential equation.

10

Page 12: MATLAB TUTORIAL BASIC

Ordinary Differential Equations

Sample Equations

Typical linear equations are

dy

dt+ 3ty = 0 t2

d2y

dt2+ 10t3y = sin t

Typical non–linear equations are

ydy

dt+ 3ty = 0 t2

d2y

dt2+ 10y4 = sin t

Exact solutions can, generally, only be obtained for linear equations but not all linear equations can

be solved exactly.

When exact solutions can not be found, information on the behaviour of the solution may be obtained

by using approximate numerical methods.

11

Page 13: MATLAB TUTORIAL BASIC

Ordinary Differential Equations

Boundary and Initial Conditions

Normally, the model of a physical problem will have a unique solution.

To achieve this, the model cannot be defined in terms of a differential equation alone.

Additional information, in the form of boundary conditions or initial conditions, must also be provided.

For a single ordinary differential equation of order m, we need to provide m additional conditions to

obtain a unique solution.

A differential equation plus boundary conditions forms a boundary value problem.

A differential equation plus initial conditions forms an initial value problem.

Solving Ordinary Differential Equations

In this course, we will use the computer software package MATLAB to produce either exact or

approximate numerical solutions to ordinary differential equations.

12

Page 14: MATLAB TUTORIAL BASIC

Problems: 1

1.1 The volume of water, V (m3), stored in a tank with variable cross sectional area is proportional to the square root of

the water height h (m) i.e. V = α√

h, where α is a known constant. At a given time, t = 0, when the height of water in

the tank is h0 (m), a valve of cross sectional area a (m2) is opened at the bottom of the tank. Water flows out through

this valve at a speed v =√

2gh (m/sec) and, at the same time, water pours into the tank at a given constant rate f

(m3/sec).

f

ahV

h0

Show that the variation of V with time, t, is governed by the differential equation

dV

dt+

a√

2gV

α= f

1.2 A lake holds a constant volume of water V (m3). Pollutant is being dumped in the lake at a variable rate of s(t) =

β e−αt (kg/sec), where α and β are known constants. At the same time a treatment plant perfectly de-contaminates

water at a constant rate of g (m3/sec).

Vg

g

s(t)

Assuming a constant distribution of pollutant concentration in the lake at any instant, derive the differential equation that

governs the amount of pollutant in the lake as a function of time.

13

Page 15: MATLAB TUTORIAL BASIC

Problems: 1

1.3 Polluted water, with a concentration of pollutant ci (kg/m3), is poured into a lake at a rate f (m3/sec). At a distant

point in the lake, there is an equal outflow of water, so that the total volume of water in the lake remains constant. A

treatment plant has been built which is capable of perfectly de–contaminating lake water at a rate of g (m3/sec).

f

V

f

gg

If the distribution of pollutant concentration in the lake, c, at any instant may be assumed to be constant, show that its

variation with time satisfies the differential equation

dc

dt+

(f + g)c

V=

fci

V

1.4 Tightly sealed 250kg drums, containing radioactive waste, are dumped at sea with zero initial velocity. It is known

that the weight under water of each drum is 300N and that the drag force Fd (N) resisting the motion may be expressed

as Fd = 1.5 v, where v (m/sec) is the velocity of the drum.

z 300 N

1.5 v

Show that the variation of the drum velocity with time, t,

is governed by the equation

dv

dt+ 0.006v = 1.2

Show also that the variation of the drum velocity with depth, z, satisfies the equation

vdv

dz+ 0.006v = 1.2

14

Page 16: MATLAB TUTORIAL BASIC

Problems: 1

1.5 A tank initially holds 1200m3 of perfectly clean water.

6 m /s3

36 m /s

At a given instant, dirty water containing pollutant at a concentration of 2kg/m3 is poured into the tank at a rate of

6m3/sec. At the same time, water is allowed to flow out of the tank at a rate of 6m3/sec, so that the volume of water in

the tank remains constant. If the distribution of pollutant concentration in the tank at any instant may be assumed to be

constant, obtain the differential equation that governs the variation of the amount of pollutant in the tank as a function

of time.

15

Page 17: MATLAB TUTORIAL BASIC

Preparing Assignment 1 for Assessment

Advice on Preparing Assignment 1 for Assessment

The following steps should be followed when preparing your solution to Assignment 1 for assess-

ment:

1. Create a document that contains your solution to the given problem. Your work should be laid out

neatly enough to be read by someone who does not know how to do the problem. Part of your job

as an engineer is not just to get the right answer, but to do this convincingly;

2. Add a front page to your document which clearly states the course code (EG–399), the assign-

ment number, your name and your student number;

3. Add to your front page the signed statement “Apart from where referenced, I confirm that I have

not received help from, or given help to, anyone else in constructing the solution to this assignment;

4. Hand your assignment to me personally at the designated lecture in week 18.

16

Page 18: MATLAB TUTORIAL BASIC

Assignment Problem 1

Assignment 1

How do children get their swings to go higher and higher? If you observe children, they lean forward or backward at

just the right moment. In effect, the children are doing work by moving their centre of gravity. In this assignment, you

will produce the equations describing a model of this problem by considering a pendulum in which the length of the

pendulum arm can vary with time. This is designed to enhance your problem solving ability, which does not simply refer

to the ability to solve an equation but also includes the process of formulating the correct equations.

The simple pendulum serves as our dynamic model of the child on a swing. One end of the pendulum is fixed at an

attachment point A, while the mass of the child is located at the other end, which is located at a distance L(t) from A

at time t. The angle between the pendulum and the vertical at time t is denoted by θ(t). The mass of the child is m kg

and the acceleration due to gravity is g = 9.81 m/sec2.

(a) Draw a free body diagram of the mass, clearly labelling all forces and coordinate systems;

(b) Let i and j denote unit vectors in the directions of increasing L and θ respectively. Prove that

di

dθ= j

dj

dθ= −i

(c) Write a vectorial expression for the net force F acting on the mass with respect to the (L, θ) coordinate system;

(d) Derive a vectorial expression for the acceleration a of the mass with respect to the (L, θ) coordinate system;

(e) Write down the equations of motion for the mass.

17

Page 19: MATLAB TUTORIAL BASIC

MATLAB: Basics

Function m–files

A function m–file is a file that contains the series of MATLAB commands that accomplish a certain

task.

Initially, we consider function m–files which (a) require no input, i.e. the values of all variables are

defined in the file; (b) output results to the screen; (c) contain commands designed to operate on

variables in the workspace.

A file filename of this type is stored with the extension .m i.e. as filename.m.

You should create a new directory for m–files created for this course, e.g. EG399 matlab files.

Sample m–files, containing the commands necessary to solve some of the examples considered

in the lectures, may be found on drive G of the School of Engineering PC network by following the

path MATLAB→work→EG399. Copy these files into your folder of MATLAB files for future use.

18

Page 20: MATLAB TUTORIAL BASIC

MATLAB: Flow Control

Flow Control

In a general function m–file, we sometimes encounter the situation that the flow of the command

execution is based upon the outcome of certain tests.

To handle this situation, MATLAB provides a number of different flow control features which are

generally based on the results of tests that employ relational and logical operators.

Relational Operators

The relational operators that can be employed within flow control statements are

Relational Operation MATLAB Operator

greater than >

greater than or equal >=

less than <

less than or equal <=

equal ==

not equal ∼=

19

Page 21: MATLAB TUTORIAL BASIC

MATLAB: Flow Control

Logical Operators

Logical operators can be employed to combine relational operators within flow control statements

e.g.

Logical Operation MATLAB Operator

and &

or |

If Statement

This allows a group of commands to be executed only if a certain logical test is satisfied.

For example, we might want to define the value of y according to

y =

3 + 2x2 if x > 5

3 otherwise

This can be achieved by the use of the commands

20

Page 22: MATLAB TUTORIAL BASIC

MATLAB: Flow Control

If Statement (continued)

y=3.;

%reset the value of y if x>5

if x>5

y=3.+2.0*x^2;

end

If/Else Statement

This also allows statements to be executed only if a certain logical test is not satisfied to be placed

after an else, e.g.

if x>5

y=3.+2.0*x^2;

else

y=3;

end

21

Page 23: MATLAB TUTORIAL BASIC

MATLAB: Flow Control

If/Elseif/Else Statement

One or more further logical tests may be added with elseif, e.g. suppose

y =

10/k2 k > 5

−10/k2 k < −5

1 otherwise

then the value of y may be determined with the commands

if k>5

y=10/k^2;

elseif k<-5

y=-10/k^2;

else

y=1;

end

Note also that flow control may be accomplished using the while statement.

22

Page 24: MATLAB TUTORIAL BASIC

MATLAB: Flow Control

For Loops

For loops allow groups of commands to be repeated a fixed number of times, e.g. suppose that we

have xj defined for 1 ≤ j ≤ 20 and that we want to set yj = x2j for each j.

In MATLAB, we can achieve this explicitly with the use of the commands

%set up an example x vector

for j=1:20

x(j)=j;

end

%now determine corresponding y vector

for j=1:20

y(j)=x(j)^2;

end

Note

For loops are executed relatively slowly within MATLAB and more efficient implementations can be

achieved by using MATLAB’s vectorization constructs, that convert for loops into equivalent vector

or matrix operations.

23

Page 25: MATLAB TUTORIAL BASIC

MATLAB: Flow Control

Break Statement

Exit from a for loop, before completion, may be achieved by the use of a break statement.

Following the execution of the break statement, control is passed to the first statement after the end

of the for loop.

Suppose we wish to evaluate

S =

∞∑

j=1

1

j3= 1 +

1

23+

1

23+ · · ·

In practice, we would specify an acceptable absolute error, ε, and evaluate

SJ =

J∑

j=1

1

j3= 1 +

1

23+

1

23+ · · · + 1

J3

where the number of terms, J , used is such that |SJ+1 − SJ | < ε.

In MATLAB, we can achieve this explicitly with the use of the commands

clear

clc

24

Page 26: MATLAB TUTORIAL BASIC

MATLAB: Flow Control

Break Statement (continued)

%set the acceptable absolute error

eps=1.0e-6;

%set the initial value for the sum SJ

SJ=0.;

%evaluate SJ by successive addition of terms 1/j^3 until for j=J

%1/J^3 is less than the specified value of eps

for j=1:1000

term=1/(j^3);

if term < eps

break

end

SJ=SJ+term;

end

%print out the value of J and SJ

fprintf(’\n number of terms added = %g\n’,j)

fprintf(’\n value of the sum SJ = %g\n’,SJ)

25

Page 27: MATLAB TUTORIAL BASIC

MATLAB: Symbolic Toolbox

Symbolic Toolbox

The Symbolic Toolbox in MATLAB provides a link to the powerful symbolic algebra program MAPLE.

The Symbolic Toolbox works with symbols, formulae and equations and can be used to provide, if

they exist, explicit formulae for the solution of ordinary differential equations.

Declaration of Symbolic Variables

Within MATLAB, symbolic variables can be defined using the syms command e.g.

>> syms a b c s

Symbolic Expressions

Using symbolic variables and integers, symbolic expressions can be created using the conventional

MATLAB mathematical operators e.g.

>> syms x

>> y=2*(x^2)+(3/4)*(x^4);

26

Page 28: MATLAB TUTORIAL BASIC

MATLAB: Symbolic Toolbox

Examples Using the Symbolic Toolbox

MATLAB can differentiate symbolic expressions e.g.

>> y=2*(x^2)+(3/4)*(x^4);

>>z=diff(y,x)

z=

4*x+3*x^3

>>w=diff(y,x,2)

w=

4+9*x^2

Indefinite integrals may be evaluated using the int command e.g.

>>yint=int(y,x)

yint=

2/3*x^3+3/20*x^5

Note that the constant of integration is always omitted.

27

Page 29: MATLAB TUTORIAL BASIC

MATLAB: Symbolic Toolbox

Examples Using the Symbolic Toolbox (continued)

The definite integral of y between the limits x=0 and x=1 may be obtained by using

>>yintd=int(y,x,0,1)

yintd= 49/60

The double command can be used to convert this symbolic result for yintd into a numerical value

as

>>double(yintd)

ans=

0.8167

Equations can be solved using the solve command e.g. to find the value y of x for which ax + b is

equal to zero, we could use the commands

>> syms a b x

>> eqn=a*x+b;

>> y=solve(eqn,x)

y =

-b/a

28

Page 30: MATLAB TUTORIAL BASIC

MATLAB: dsolve

Solving Ordinary Differential Equations

The exact analytical solution of an ordinary differential equation (if it exists!) can be found by using

the MATLAB command dsolve.

Examples of the Use of dsolve

1. To find the general solution of the equation

dy

dt+ 3y = 10

In MATLAB, this can be achieved with the use of dsolve as

>>sol=dsolve(’Dy+3*y=10’,’t’)

sol

= 10/3+exp(-3*t)*C1

Here, C1 is an arbitrary constant.

29

Page 31: MATLAB TUTORIAL BASIC

MATLAB: dsolve

Examples of the Use of dsolve (continued)

2. Suppose we wish to impose the initial condition y=2 at t=0. This may be accomplished directly

using

>>sol=dsolve(’Dy+3*y=10’,’y(0)=2’,’t’)

sol=

10/3-4/3*exp(-3*t)

Alternatively, the commands shown in file example 1.m can be used to obtain this particular solution

from the general solution obtained previously. This is done by determining the value of the constant

C1 by imposing the initial condition explicitly.

30

Page 32: MATLAB TUTORIAL BASIC

MATLAB: Graphics

Plotting Solutions

The variation of the symbolic variable representing the solution of an ordinary differential equation

may be readily displayed using the plot command e.g.>>syms t

>>sol=dsolve(’Dy+3*y=10’,’y(0)=2’,’t’)

sol=

10/3-4/3*exp(-3*t)

>>for i=1:101

tn(i)=(i-1)*0.1;

soln(i)=subs(sol,t,tn(i));

end

>> plot(tn,soln)

0 1 2 3 4 5 6 7 8 9 102

2.5

3

3.5

Labelling can also be added, e.g. with the commands

>> grid

>> title(’solution of differential equation’)

>> xlabel(’time, t’)

>> ylabel(’solution, y’)0 1 2 3 4 5 6 7 8 9 10

2

2.5

3

3.5solution of differential equation

time, t

solu

tion,

y

31

Page 33: MATLAB TUTORIAL BASIC

Problems: 2

2.1 Solve the equation

dy

dx+ 4y = 8x2

2.2 The volume of water, V (m3), stored in a tank with variable cross sectional area is proportional to the square root of

the water height h (m) i.e. V = α√

h, where α is a known constant. At a given time, t = 0, when the height of water in

the tank is h0 (m), a valve of cross sectional area a (m2) is opened at the bottom of the tank. Water flows out through

this valve at a speed v =√

2gh (m/sec) and, at the same time, water pours into the tank at a given constant rate f

(m3/sec).

f

ahV

h0

Show that, as t becomes very large, the volume of water in the tank tends to (fα)/(a√

2g) (m3).

32

Page 34: MATLAB TUTORIAL BASIC

Problems: 2

2.3 A lake holds a constant volume of water V (m3). Pollutant is being dumped in the lake at a variable rate of s(t) =

β e−αt (kg/sec), where α and β are known constants. At the same time a treatment plant perfectly de-contaminates

water at a constant rate of g (m3/sec).

Vg

g

s(t)

Assuming α 6= g/V , show that the amount of pollutant, A, in the lake at time t may be written as

A = C1e−(gt/V ) +

β

(g − αV )e−αt

2.4 Polluted water, with a concentration of pollutant ci (kg/m3), is poured into a lake at a rate f (m3/sec). At a distant

point in the lake, there is an equal outflow of water, so that the total volume of water in the lake remains constant. A

treatment plant has been built which is capable of perfectly de-contaminating lake water at a rate of g (m3/sec).

f

V

f

gg

If the concentration of pollutant in the lake, c, is assumed to be uniform at any instant, show that

c = C1 exp [−(f + g)t/V ] +fci

(f + g)

where C1 is a constant.

33

Page 35: MATLAB TUTORIAL BASIC

Problems: 2

2.5 Tightly sealed 250kg drums, containing radioactive waste, are dumped at sea with zero initial velocity. The drums

will crack on impact with the ocean floor if their speed exceeds 13m/sec. It is known that the weight under water of each

drum is 300N and that the drag force FdN resisting the motion is given to be Fd = 1.5v, where v (m/sec) is the velocity

of the drum.

z 300 N

1.5 vDetermine the variation of the drum velocity

with time during the fall.

Assuming that a drum takes an infinite time to reach the ocean floor, obtain the velocity on impact. Plot the velocity of

the drum as a function of the depth and find the maximum depth of water in which the drums can be dumped, if cracking

is to be avoided.

2.6 A tank initially holds 1200m3 of perfectly clean water. At a given instant, dirty water containing pollutant at a

concentration of 2kg/m3 is poured into the tank at a rate of 6m3/sec. At the same time, water is allowed to flow out of

the tank at a rate of 6m3/sec, so that the volume of water in the tank remains constant.

6 m /s3

36 m /s

Assuming uniform concentration of pollutant in

the tank, plot this concentration as a function of

time, t, for 0 ≤ t ≤ 1000sec.

34

Page 36: MATLAB TUTORIAL BASIC

MATLAB: dsolve for Systems of Equations

Coupled First Order Equation Systems

Frequently, the modelling of a physical problem produces a coupled set of two or more first order

differential equations. This is an equation system and simple equation systems may also be solved

using the MATLAB command dsolve.

Example

The coupled equation system

dy

dt+ 4y + z = e−t dz

dt− y + 2z = sin 3t

may be solved by using the command

>> syms t

>> sol=dsolve(’Dy+4*y+z=exp(-t),Dz-y+2*z=sin(3*t)’,’t’);

>> sol1=sol.y

sol1= exp(-3*t)*C2+exp(-3*t)*t*C1+1/18*cos(3*t)+1/4*exp(-t)

>> sol2=sol.z

sol2=-exp(-3*t)*C2-exp(-3*t)*t*C1-exp(-3*t)*C1+1/6*sin(3*t)-2/9*cos(3*t)+1/4*exp(-t)

35

Page 37: MATLAB TUTORIAL BASIC

MATLAB: dsolve for Systems of Equations

Example

The coupled initial value problem (file example 2.m)

dy

dt+ 4y + z = e−t dz

dt− y + 2z = sin3t y = 1 and z = 1 at t = 0

may be solved by using the commands

>> syms t

>> sol=dsolve(’Dy+4*y+z=exp(-t),Dz-y+2*z=sin(3*t)’,’y(0)=1,z(0)=1’,’t’);

>> sol1=sol.y

sol1 =

25/36*exp(-3*t)-5/3*exp(-3*t)*t+1/18*cos(3*t)+1/4*exp(-t)

>> sol2=sol.z

sol2=

35/36*exp(-3*t)+5/3*exp(-3*t)*t+1/6*sin(3*t)+1/4*exp(-t)-2/9*cos(3*t)

36

Page 38: MATLAB TUTORIAL BASIC

MATLAB: dsolve for Systems of Equations

Example (continued)

To plot the variation of y and z with t we can use the commands

for i=1:101

tn(i)=(i-1)*0.1;

sol1n(i)=subs(sol1,t,tn(i));

sol2n(i)=subs(sol2,t,tn(i));

end

plot(tn,sol1n,’-.’)

hold on

plot(tn,sol2n,’:’)

legend(’y’,’z’)

title(’equation system’)

xlabel(’t’)

ylabel(’solution’)

0 2 4 6 8 10−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

tso

lutio

n

equation system

yz

37

Page 39: MATLAB TUTORIAL BASIC

MATLAB: dsolve for Higher Order Equations

Higher Order Problems

Frequently, we encounter problems involving ordinary differential equations of order more than one

e.g. when modelling a certain spring/mass system with external forcing term, the governing differ-

ential equation for the displacement of the mass takes the form

d2y

dt2+ 144y = cos(11t) y = 0 and

dy

dt= 0 at t = 0

To solve this problem, we can re–write the single equation as a system of first order equations. For

this example, this is achieved by introducing the new variable

u =dy

dt

and replacing the single second order governing equation by the system of two coupled first order

equations

dy

dt= u

du

dt= −144y + cos(11t)

and this may now be solved using dsolve, subject to the initial conditions y(0) = 0, u(0) = 0.

38

Page 40: MATLAB TUTORIAL BASIC

MATLAB: dsolve

Higher Order Problems (continued)

To obtain the solution to this problem use the commands (file example 3.m)

>>syms t

>>sol=dsolve(’Dy=u,Du=-144*y+cos(11*t)’,’y(0)=0,u(0)=0’,’t’)

>>sol1=sol.y

sol1=-1/23*cos(12*t)+1/23*cos(11*t)

>>for i=1:301

tn(i)=(i-1)*0.1;

sol1n(i)=subs(sol1,t,tn(i));

end

>>plot(tn,sol1n)

0 5 10 15 20 25 30−0.1

−0.08

−0.06

−0.04

−0.02

0

0.02

0.04

0.06

0.08

0.1

39

Page 41: MATLAB TUTORIAL BASIC

Problems: 3

3.1 Solve the equations

(a)d2y

dx2+ y = 6ex + 6sinx

(b)d4y

dx4− 16y = 0

3.2 Solve the system of differential equationsdy

dt= y − 2z

dz

dt= 2y + z

and obtain the general solutions for the functions y(t) and z(t).

3.3 The vibration of a certain mechanical system is governed by the differential equations

d2y

dt2= −2y + z

d2z

dt2= −2z + y

Determine the solution to this problem corresponding to the initial conditions

y = 1dy

dt=

√3 z = 1

dz

dt= −

√3 at t = 0

3.4 For thermal analysis purposes, a house is regarded as consisting of two zones. Zone 1 is the attic area and zone

2 is the living area. The living area, which has a heat capacity of (1/4)oC/kw, is cooled by an air conditioning unit that

removes 30kw/hour. The time constant for heat transfer between zone 1 and the outside is 2 hours, between zone 2

and the outside is 4 hours and between the two zones is 4 hours. Initially, the air conditioner is switched off and the

temperature in both zones is equal to the outside temperature of 37oC. At time t = 0, the air conditioner is switched

on. Assuming the outside temperature remains constant at 37oC, plot the variation in temperature with time, t, for both

zones 1 and 2 for 0 ≤ t ≤ 30 hours. From your plot, estimate the temperature in the attic zone 1 for large values of the

time.

40

Page 42: MATLAB TUTORIAL BASIC

Problems: 3

3.5 Two tanks, 1 and 2, each hold an equal and constant volume V = 500 litres of water. The tanks are connected

by two pipes that carry opposite but equal flows f = 2 litres/sec. Initially, the water in tank 1 contains a concentration

0.01 kg/litre of a certain pollutant while the water in tank 2 is clean.

V

f

V

f

Show that the differential equations that govern the amounts of pollutant y(t) and z(t), in tanks 1 and 2 respectively,

are of the form

dy

dt= −α y + α z

dz

dt= α y − α z

and obtain the value of the constant α.

Determine the solution of this system of equations and plot the variation of the amount of pollutant in each tank with

time for 0 ≤ t ≤ 1000 sec.

3.6 A certain system consists of two large tanks, each holding 100 litres of liquid, which are interconnected by two

pipes. Through these pipes, liquid flows from tank 1 into tank 2 at a rate of 3 litres/min and from tank 2 into tank 1 at a

rate of 1 litre/min. In addition, polluted liquid with a concentration of 2 kg/litre flows, from outside the system, into tank

1 at a rate of 6 litres/min while liquid flows out of the system from tank 1 at 4 litres/min and from tank 2 at 2 litres/min.

If the concentration of pollutant is taken as uniform within each tank at any instant, with initially tank 1 containing pure

water and tank 2 containing 200 kg of pollutant, plot the variation of the mass of pollutant within each tank with time t,

for 0 ≤ t ≤ 200 min. Use your plot to determine the amount of pollutant in each tank for large values of the time.

41

Page 43: MATLAB TUTORIAL BASIC

Problems: 3

3.7 A mountain climber starts from her base camp at a certain time, t = 0. As she climbs, fatigue and oxygen

deprivation take their toll so that, at any instant, the rate at which the square, Z, of her elevation, h, is increasing is

found to be constant. At time t = 6 hours, she is at an elevation of 6 000 metres and she reaches the top of the

mountain, at 6 500 metres, at time t = 8 hours.

1. Derive a second order differential equation for Z and obtain the solution using dsolve;

2. Determine the elevation of the base camp;

3. Plot the variation of the climber’s height h with time t for 0 ≤ t ≤ 8 hours.

42

Page 44: MATLAB TUTORIAL BASIC

Heaviside Function

Heaviside (Step) Function

In problems in dynamics, we frequently encounter the situation in which it is not possible to define

a time–varying applied load, f(t), in a single mathematical expression e.g.

f(t) =

0, t < aF, t > a

or

f(t) =

t2, t < aa2, t > a

In problems in statics, a space–varying applied load, ω(x), might be defined as

ω(x) =

x2, 0 < x < b0, b < x < 1

Solving differential equations involving loads defined in this manner introduces certain complica-

tions.

Using the Heaviside function to represent the load as a single expression enables such equations

to be solved directly.

43

Page 45: MATLAB TUTORIAL BASIC

Heaviside Function

Definition of the Heaviside Function

The Heaviside function, H(t − a), is defined as

H(t − a) =

0, t < a1, t > a

Given a function, f(t), what is the function f(t)H(t − a)?

Using the definition of the Heaviside function, we see that

f(t)H(t − a) =

0, t < af(t), t > a

i.e. the function f(t) is effectively switched on at time t = a.

Note that the function f(t) + [g(t)− f(t)]H(t− a) is equal to f(t) for t < a and to g(t) for t > a.

44

Page 46: MATLAB TUTORIAL BASIC

MATLAB: Heaviside Function

Using the Heaviside Function

We now see how the Heaviside function may be used to construct piecewise continuous functions

by switching functions on and off at appropriate times, e.g. the function

f(t) =

0, t < 0,

1, 0 < t < 1,

t2, 1 < t < 3,

sin 2t, t > 3

may be written as the single expression

f(t) = 0 + (1 − 0)H(t) + (t2 − 1)H(t − 1) + (sin 2t − t2)H(t − 3)

45

Page 47: MATLAB TUTORIAL BASIC

MATLAB: Heaviside Function

Working with the Heaviside Function in MATLAB

The function

f(t) = 0 + (1 − 0)H(t) + (t2 − 1)H(t − 1) + (sin 2t − t2)H(t − 3)

may be defined and plotted in MATLAB with the commands (file example 5.m)

syms t

f=’heaviside(t)+(t^2-1)*heaviside(t-1)+(sin(2*t)-t^2)*heaviside(t-3)’;

%plot the loading function

for i=1:1000

tn(i)=0.001+(i-1)*0.01;

fn(i)=subs(f,t,tn(i));

end

plot(tn,fn)

0 2 4 6 8 10−1

0

1

2

3

4

5

6

7

8

9

46

Page 48: MATLAB TUTORIAL BASIC

MATLAB: Heaviside Function

Example

Solve the initial value problem

d2y

dt2+ 3

dy

dt+ y = f(t) y = 1 and

dy

dt= 1 at t = 0

where

f(t) =

0, t < 0,

1, 0 < t < 1,

t2, 1 < t < 3,

sin 2t, t > 3

In MATLAB, this process can be accomplished by using the commands (file example 6.m)

clear

clf

clc

%

syms t

sol=dsolve(...

’Dy=u,Du=-3*u-y+heaviside(t)+(t^2-1)*heaviside(t-1)+(sin(2*t)-t^2)*heaviside(t-3)’,...

’y(0)=1,u(0)=1’,’t’);

47

Page 49: MATLAB TUTORIAL BASIC

MATLAB: Heaviside Function

Example (continued)

sol1=sol.y;

for i=1:800

tn(i)=0.001+0.02*(i-1);

sol1n(i)=subs(sol1,t,tn(i));

end

plot(tn,sol1n)

xlabel(’time, t’)

ylabel(’solution, y’)

0 2 4 6 8 10 12 14 16−0.5

0

0.5

1

1.5

2

2.5

3

time, t

solu

tion,

y

48

Page 50: MATLAB TUTORIAL BASIC

Dirac Function

Dirac (Delta) Function

Another useful function is the Dirac delta function, which is normally written as δ(t−a) and has the

definition

δ(t − a) = 0 t 6= a

and, in addition, is such that, for any f(t),

∫ β

α

δ(t − a)f(t)dt =

0, if α, β < a or α, β > a

f(a), if α < a and β > a

Note that, by setting f(t) = 1, it follows that∫ a+

a−

δ(t − a)dt = 1

What applications could employ such a function?

49

Page 51: MATLAB TUTORIAL BASIC

Dirac Function

Applications Employing the Delta Function

Consider a particle moving under the action of an external force, f(t), which takes the form of an

impulsive force F at time t = a. The effect of this impulsive force is to change the momentum of

the particle by an amount F at time t = a, without change of location.

The governing equation for the moving particle is clearly

mdv

dt= f(t)

but what is the correct form for f(t) in this case?

The answer to this question is that we should take

f(t) = Fδ(t − a)

as this means that

f(t) = 0 for t < a and t > a

as required, while integrating the equation of motion from t = α to t = β gives

[mv]t=βt=α = [mv]t=β − [mv]t=α =

∫ β

α

Fδ(t − a)dt

50

Page 52: MATLAB TUTORIAL BASIC

Dirac Function

Applications Employing the Delta Function (continued)

We see that if both α < a and β < a or if both α > a and β > a then

[mv]t=β − [mv]t=α = 0

It follows that, in these cases, there is no change in the momentum of the system over the time

interval α ≤ t ≤ β, as required.

However, if α = a − ε and β = a + ε, where ε is any positive number, then

[mv]t=β − [mv]t=α =

∫ a+ε

a−ε

Fδ(t − a)dt = F

This implies a change of momentum of amount F at time t = a, as required.

Similarly, if a light cable is subjected to a point load P at x = a, the equation governing the deflected

shape is

d2y

dx2=

ω(x)

Hwhere ω(x), the load per unit length on the cable can, in this case, be expressed as

ω(x) = Pδ(x − a)

51

Page 53: MATLAB TUTORIAL BASIC

MATLAB: Dirac Function

Example

The deflection y of a certain spring/mass system is the solution of the problem

d2y

dt2+ 2

dy

dt+ 10y = 1 + 5δ(t − 5) y = 1 and

dy

dt= 2 at t = 0

The solution can be obtained using the MATLAB commands (file example 7.m)

clear

clf

clc

syms t

sol=dsolve(...

’Dy=u,Du=-2*u-10*y+1+5*dirac(t-5)’,...

’y(0)=1,u(0)=2’,’t’);

sol1=sol.y;

for i=1:1000

tn(i)=0.001+(i-1)*0.01;

sol1n(i)=subs(sol1,t,tn(i));

end

plot(tn,sol1n)

0 1 2 3 4 5 6 7 8 9 10−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

1.2

52

Page 54: MATLAB TUTORIAL BASIC

Problems: 4

4.1 A particle of unit mass moves along the y–axis under the influence of an external force f(t) in the y direction. If the

particle starts from rest at the point y = 0 at time t = 0 and if

f(t) =

1 0 ≤ t ≤ a/21 + (t − a/2)/a a/2 < t

show that the particle is at the point y = 25a2/48 at time t = a.

4.2 Determine the deflection of a damped spring mass system, subjected to a unit impulse at time t = 1, which is

governed by the equation

d2y

dt2+ 3

dy

dt+ 2y = δ(t − 1)

given that the system is at rest, at zero displacement, at time t = 0. Plot the solution y for 0 ≤ t ≤ 10.

4.3. The displacement y(t) of a vibrating mechanical system is governed by the equation

d2y

dt2+ y = f(t)

where

f(t) =

20 0 < t < 3π0 3π < t < 4π20 4π < t

If y = 10,dy/dt = 0 at t = 0, plot the variation of y with t for 0 ≤ t ≤ 30.

53

Page 55: MATLAB TUTORIAL BASIC

Problems: 4

4.4 The displacement, y(t), of a certain mechanical system is governed by the equation

d2y

dt2+ y = f(t)

where the external force, f(t), is defined by

f(t) =

1, t < 10, t > 1

plus an impulse I = 1 at time t = 2. At time t = 0, the system is at rest, with zero displacement. Plot the variation of

y with t for 0 ≤ t ≤ 8 and determine the displacement and the velocity at time t = 3.

4.5 A vibrating mechanical system is subjected to an impulse at time t = π, such that the displacement y(t) of the

system satisfies the equation

d2y

dt2+ 9y = 3δ(t − π)

where δ denotes the Dirac delta function. Given that

y = 1 anddy

dt= 0 at t = 0

determine the displacement at time t = 13π/12 and plot the variation of y with t for 0 ≤ t ≤ 10.

54

Page 56: MATLAB TUTORIAL BASIC

Problems: 4

4.6 The light cable of a suspension bridge supports a light bridge deck that is 100 metres in length. The coordinate x

is measured from one end of the deck and, for 0 < x < 60 metres, the deck is loaded with a uniformly distributed load

of 15 kN/metre. In addition, there is a point load of 400 kN applied to the deck at x = 75 metres. The location of the

cable supporting the bridge deck is denoted by y(x) and the cable is subjected to the boundary conditions

[y]x=0 = 10 metres [y]x=100 = 30 metres

1. If the horizontal component of the tension in the cable H = 500 kN, use dsolve to obtain y(x).

2. Determine the cable location when (i) x = 20 metres; (ii) x = 50 metres; (iii) x = 80 metres.

3. Plot the deflected cable shape.

4.7 A steel beam, of constant square cross section, is of length L = 0.5 m. For this beam, the Young’s Modulus

E=2× 1011 Pa and the moment of inertia of the cross section I=2.13× 10−11 m4. The coordinate x is measured from

one end of the beam and, for 0 < x < 0.4 × L m, the beam is loaded with a uniformly distributed load of 5 N/m. In

addition, there is a point load of 40 N applied to the beam at x = 0.75 × L m. The deflection of the beam, denoted by

y(x) in metres, satisfies the equation

d4y

dx4= −ω(x)

EI0 < x < L

where ω(x) denotes the load per unit length on the beam. At the end x = 0, the deflection is zero and the beam is

clamped horizontally i.e.

y = 0 anddy

dx= 0 at x = 0

55

Page 57: MATLAB TUTORIAL BASIC

Problems: 4

4.7 (continued) Use dsolve to obtain the form of the deflection, and plot the deflected shape, when

(a) the beam is clamped horizontally at the end x = L, so that

y = 0 anddy

dx= 0 at x = L

(b) the beam is free at the end x = L, so that

d2y

dx2= 0 and

d3y

dx3= 0 at x = L

(c) the beam is freely hinged, with zero deflection, at the end x = L, so that

y = 0 andd2y

dx2= 0 at x = L

56

Page 58: MATLAB TUTORIAL BASIC

Numerical Methods

The Need for Approximate Solution Methods

Although we have seen several examples of differential equations that can be explicitly solved, many

ordinary differential equations are not amenable to exact solution, e.g. if we use dsolve to solve the

equation

ydy

dt+ y = tan t

we obtain

>> sol=dsolve(’Dy+1=tan(t)/y’,’t’)

Warning: Explicit solution could not be found.

In such cases we have to turn to approximate methods if we are to gain any information about the

nature of the solution y(t).

We will illustrate initially how this may be accomplished, using a finite difference method on the

range t1 = 0 ≤ t ≤ T = tN , for the typical initial value problem

dy

dt= f rhs(t, y) y(0) = yzero

57

Page 59: MATLAB TUTORIAL BASIC

Numerical Methods

Approximating the First Derivative by the Finite Difference Method

Define a set of N points on the range t1 = 0 ≤ t ≤ T = tN according to

h = T/(N − 1) tj = (j − 1)h j = 1,2, · · · , N − 1, N

Let y(tj) = yj and note that the slope of the tangent to y(t) at t = tj isdy

dt

j

Approximate the slope of the tangent

by using the slope of the straight

line joining the points (tj, yj) and

(tj+1, yj+1) i.e.

dy

dt

j

≈ yj+1 − yj

tj+1 − tj=

yj+1 − yj

h

This is the forward difference approxi-

mation to the first derivative. tttt

t

t t tt

y

0

1 2 j j+1j-1 N-1 N

tangent to y(t) at t

y(t)

j

y

yj

j+1

h

58

Page 60: MATLAB TUTORIAL BASIC

Numerical Methods

Euler’s Method for the Initial Value Problem

If we evaluate our differential equation at the point t = tj we have that

dy

dt

j

= f rhs(tj, yj)

and this equation may be approximated, using the forward difference approximation to the first

derivative asyj+1 − yj

h= f rhs(tj, yj)

Since we are given that y(0) = y(t1) = y1 = yzero, this leads to the iterative scheme

yj+1 = yj + hf rhs(tj, yj) j = 1,2, · · · , N − 2, N − 1

for successively computing approximate values to the solution at the points t2, t3, · · · , tN−1, tN .

Thus

y2 = y1 + hf rhs(t1, y1) = yzero + hf rhs(t1, yzero) t1 = 0

y3 = y2 + hf rhs(t2, y2) = y2 + hf rhs(t2, y2) t2 = h

... ... ...

yN = yN−1 + hf rhs(tN−1, yN−1) = yN−1 + hf rhs(tN−1, yN−1) tN−1 = (N − 2)h

59

Page 61: MATLAB TUTORIAL BASIC

Numerical Methods

Euler’s Method in MATLAB

In Euler’s method we work with numerical values, not symbols.

The starting point for a MATLAB implementation is an algorithmic description of the tasks involved

in using Euler’s method.

Algorithm for Euler’s Method

1. define the function f rhs(t, y);

2. define the end point t = T for the computation;

3. define the number of points N to be used over the time interval [0,T];

4. define the initial value of the solution, yzero = value of y at t=0;

5. compute the interval length h = T/(N − 1);

6. set up the tj points as t(j) = (j − 1)h for 1 ≤ j ≤ N ;

60

Page 62: MATLAB TUTORIAL BASIC

Numerical Methods

Algorithm for Euler’s Method (continued)

7. set the initial condition y(1) = yzero;

8. use Euler’s Method to find the required yj values from

y(j + 1) = y(j) + hf rhs(t(j), y(j)) j = 1,2, · · · , N − 1

9. plot the results.

To enable us to convert a numerical algorithm of this form into a set of MATLAB commands, we first

need to study some of the additional features provided by MATLAB.

61

Page 63: MATLAB TUTORIAL BASIC

MATLAB: More on m–Files

More on Function m–files

Function m–files can also be written to accept and return arguments in exactly the same fashion as

the standard MATLAB functions, such as sin, cos, etc.

Example

Consider the problem of evaluating the function

f(x) =x2

(1 + x)sin x

If we need to determine the value of the f(x) for a large number of different values of x, this can be

conveniently accomplished by writing a function m–file that will accept a value of x and return the

corresponding value of f(x).

A function m–file f.m that would achieve this could employ the commands

62

Page 64: MATLAB TUTORIAL BASIC

MATLAB: More on m–Files

Example (continued)

function [f_value]=f(x)

%f determines the value, f_value, of the function at x

% f_value=(x^2/sqrt(1+x))*sin(x) at x

f_value=((x*x)/sqrt(1+x))*sin(x)

%

With this function defined, typing

a=f(3)

in the command window produces the output

a =

0.6350

63

Page 65: MATLAB TUTORIAL BASIC

MATLAB: More on m–Files

Example (continued)

An alternative mode of operation, with the function m–file f.m defined, could be to determine the

value of f(x), for any given value of x, by using a function m–file my function.m defined as

function my_function

%my_function inputs a value of x and determines the corresponding value of

% f(x)=(x^2/sqrt(1+x))*sin(x)

clc

clear

%

fprintf(’\n Evaluate the function f\n’)

%

x=input(’input value of x = ’)

%

fx=f(x1);

fprintf(’\n Value of f %g\n’,fx)

64

Page 66: MATLAB TUTORIAL BASIC

MATLAB: More on m–Files

Example

Suppose you want to write a function m–file with the task of plotting the distribution of the function

f(x) that has already been defined in the function m–file f.m.

A possible m–file my function plot.m to accomplish this could be

function my_function_plot

%my_function_plot To plot the distribution of the function f(x)

% for -0.5<x<3

% f(x) is defined in the separate m-file f.m

%

%construct a set of x(j) values

%and determine corresponding values y(j)=f(x(j))

for j=1:40

x(j)=-0.5+(3.5/39)*(j-1);

y(j)=f(x(j));

end

plot(x,y)

%

65

Page 67: MATLAB TUTORIAL BASIC

More on MATLAB

Global Variables

Variables used within a function are local to that function’s workspace.

Variables may exist in more than one workspace if they are transferred in the function argument list

or if they are declared as global variables via the global command.

Sub–Functions

Note that a function m–file may contain other functions, called sub–functions, which appear (in any

order) after the main function.

Sub–functions are visible only to the main function and to the other sub–functions.

Typically, they carry out a task that is unlikely to be needed in any other m–file and they can,

therefore, be used to avoid a proliferation of m–files.

66

Page 68: MATLAB TUTORIAL BASIC

MATLAB: More on m–Files

Example

To plot our function f(x) we could produce the modified function m–file my function plot new.m

which contains the sub–function f as follows:

function my_function_plot_new

%my_function_plot_new plots the distribution of the function f(x)

% for -0.5<x<3

% f(x) is defined as a sub-function

%

%construct a set of x values

%and determine corresponding y values

for j=1:40

x(j)=-0.5+(3.5/39)*(j-1);

y(j)=f(x(j));

end

plot(x,y)

%

67

Page 69: MATLAB TUTORIAL BASIC

MATLAB: More on m–Files

Example (continued)

%-----------------------------------------------------------------------

% subfunction

%----------------------------------------------------------------------

function [f_value]=f(x)

%f_1 determines the value, f_value, of the function f at x

% i.e. f_value=(x*^2/sqrt(x+1))*sin(x)

f_value=((x*x)/sqrt(x+1))*sin(x);

Executing the commands in the m–file

my function plot new.m produces the plot

−0.5 0 0.5 1 1.5 2 2.5 3−0.5

0

0.5

1

1.5

2

2.5

68

Page 70: MATLAB TUTORIAL BASIC

Numerical Methods

Example

Use MATLAB to solve the initial value problem

dy

dt=

t

yy(0) = 1 0 ≤ t ≤ 2

by Euler’s method.

Using the algorithmic description we detailed previously, we construct a function m–file, euler m,

for undertaking Euler’s method for a general initial value problem. The right hand side function,

f rhs(t, y), (= t/y in this example) will be defined as a sub–function f rhs.m. For this example,

the exact solution is known to be y =√

x2 + 1 and so the performance of the approximate method

can be investigated.

The function m–file could take the form (file example 8.m)

function example_8

%example_8 solves an initial value problem using Euler’s Method

% ode: dy/dt=f_rhs(t,y);

% RHS function f_rhs: defined as sub-function f_rhs

% initial value yzero=1

69

Page 71: MATLAB TUTORIAL BASIC

Numerical Methods

Example (continued)

clear

clc

clf

%define the end point t=T for the computation

T=2;

%define the number of points to be used over [0,T]

N=50;

%define the initial value of the solution at t=0

yzero=1;

%compute the interval length

h=T/(N-1);

%set up the tj points

for j=1:N

t(j)=(j-1)*h;

end

70

Page 72: MATLAB TUTORIAL BASIC

Numerical Methods

Example (continued)

%use Euler’s Method to find the corresponding y values

y(1)=yzero;

for j=1:N-1

y(j+1)=y(j)+h*f_rhs(t(j),y(j));

end

%plot the results

plot(t,y,’o’)

hold on

%plot the exact solution for the equation dy/dt=(t/y)

for j=1:N

yexact(j)=sqrt(t(j)^2+1);

end

plot(t,yexact)

legend(’Euler, N=50’,’exact’)

71

Page 73: MATLAB TUTORIAL BASIC

Numerical Methods

Example (continued)

%

% Sub-function

%

function [f_value]=f_rhs(t,y)

%f_rhs(y,t) computes the value the RHS function at t and y

% f_value is the value of the function at t, y

%

f_value=t/y;

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 21

1.5

2

2.5Euler, N=50exact

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 21

1.5

2

2.5Euler, N=20exact

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 21

1.5

2

2.5Euler, N=5exact

N = 50 N = 20 N = 5

72

Page 74: MATLAB TUTORIAL BASIC

Numerical Methods

System of First Order Equations

An initial value problem involving a system of coupled first order equations, such as

dy

dt= f rhs(t, y, z)

dz

dt= g rhs(t, y, z)

can be solved in a similar fashion using Euler’s method, with two function m–files, or sub–functions,

employed to define the right hand side functions f rhs(t, y, z) and g rhs(t, y, z).

73

Page 75: MATLAB TUTORIAL BASIC

Numerical Methods

Higher Order Initial Value Problems

The Euler method can also be employed to provide the solution to initial value problems involving

ordinary differential equations of order more than one, such as the problem

md2y

dt2+ c

dy

dt+ ω2y = f(t) y(0) = yzero

dy

dt

t=0

= vzero

which is encountered when modelling the displacement y of a spring/mass/dashpot system with

external forcing term. To solve this problem numerically, we first re–write the single equation as a

system of first order equations. For example, here we define

u =dy

dt

and replace the single second order governing equation by the system of two coupled first order

equationsdy

dt= u

du

dt= −cu

m− ω2y

m+

f(t)

m

and this may now be solved using Euler’s method, subject to the initial conditions y(0) = yzero,

u(0) = vzero.

74

Page 76: MATLAB TUTORIAL BASIC

Problems: 5

5.1 The headlamp mirror of a car is designed to reflect light given off by the headlamp in rays parallel to the road surface.

By using optics, it is possible to derive the differential equation

dy

dx=

−x +(

x2 + y2)1/2

ythat governs the shape of the mirror. The mirror is designed so that the distance of the mirror directly above the lamp is

1 cm, i.e. y(0)=1. Use Euler’s method to plot the mirror shape for 0 ≤ x ≤ 5 cm and print the approximation of y(5).

5.2 An object is released, with zero initial velocity, from a stationary hot air balloon and drops to earth. Given that the

velocity v of the object varies with time t according todv

dt+ 2.2v = 32

obtain the solution using Euler’s method for 0 ≤ t ≤ 5. Plot the variation of v with t and estimate the terminal velocity

(i.e. the velocity attained for large values of t) of the object.

5.3 A mathematical model of combat between conventional and guerilla fighters is given by the systemdy

dt= −ayz

dz

dt= −by

where a and b are effectiveness coefficients and y and z denote the number of guerilla and conventional troops respec-

tively. In a combat model for which y(0) = 10, z(0) = 15, a = 0.1 and b = 1, obtain the solution using Euler’s

method for 0 ≤ t ≤ 6. Plot this solution and determine which group will be successful.

5.4 An undamped weight of mass 0.55 (kg) is attached to one end of a spring, with spring constant 5.4 (N/m). The other

end of the spring is fixed. The weight moves in a straight line, on a rough horizontal surface that exerts a resistive force

(N) equal to three times the speed, under the influence of an external force F = 2sin 2t (N). At a certain time t = 0,

the system is at rest and the spring extension y = 0. Plot the variation of y with t for 0 ≤ t ≤ 10 sec. Estimate the

value of y (m) at time t = 3 (sec).

75

Page 77: MATLAB TUTORIAL BASIC

Numerical Methods

MATLAB Commands for Obtaining Numerical Solutions to Initial Value Problems

In MATLAB, a numerical solution to an initial value problem may be found using the ode45 command.

This is designed to produce a solution to the initial value problem

dy

dt= f rhs(t, y) y (t1) = yzero

The nature of the function f rhs(t, y) must be defined in a function m–file or as a sub–function.

76

Page 78: MATLAB TUTORIAL BASIC

Numerical Methods

The ode45 Command

To illustrate the use of the ode45 command, consider again the solution of the initial value problem

dy

dt=

t

yy(0) = 1

This problem may be solved in MATLAB by setting up the function m–file ode sol.m containing the

commands

function ode_sol

%ode_sol solves an initial value problem using ode45

% ode: dy/dt=f_rhs(t,y);

% f_rhs: defined as a sub-function

% initial value yzero=1

%

clear

clc

yzero=1;

tspan=[0 2];

77

Page 79: MATLAB TUTORIAL BASIC

Numerical Methods

The ode45 Command (continued)

[tn,soln]=ode45(@f_rhs,tspan,yzero);

plot(tn,soln,’o--’)

%---------------------------------------------------------------

% sub-function

%--------------------------------------------------------------

function [f_value]=f_rhs(t,y)

%f_rhs(y,t) computes the value of f_rhs at t and y

%

f_value=t/y;

0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 21

1.5

2

2.5

78

Page 80: MATLAB TUTORIAL BASIC

Numerical Methods

Solving Systems of First Order Equations with ode45

To illustrate the application of ode45 to the solution of a system of first order equations, we consider

an example involving an initial value problem solved previously with dsolve.

Example

dy

dt+ 4y + z = e−t dz

dt− y + 2z = sin 3t y(0) = 1 z(0) = 1

In this case, we work with the system expressed in the vector form

dy

dt= f rhs(t, y) y(0) = yzero

where here

y =

y

z

f rhs =

−4y − z + e−t

y − 2z + sin 3t

yzero =

1

1

To solve this system using ode45, we write a function m–file containing the necessary commands

(file example 9.m), with the right hand side column vector f rhs defined as a sub–function.

79

Page 81: MATLAB TUTORIAL BASIC

Numerical Methods

Example (continued)

function example_9

%example_9 integrate a system of odes using ode45

% ode: dy/dt=f_rhs(t,y) initial value: yzero

% f_rhs defined as a sub-function f_rhs

clc clear tspan=[0 10]; yzero=[1 1];

[tn,soln]=ode45(@f_rhs,tspan,yzero);

sol1n=soln(:,1);

sol2n=soln(:,2);

plot(tn,sol1n,’o’)

hold

plot(tn,sol2n,’+’)

xlabel(’t’)

ylabel(’numerical_solution’)

legend(’y’,’z’)

0 2 4 6 8 10−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

t

num

eric

al s

olut

ion

yz

80

Page 82: MATLAB TUTORIAL BASIC

Numerical Methods

Example (continued)

%---------------------------------------------------------------------

% sub-function

%--------------------------------------------------------------------

function [f_value]=f_rhs(t,y)

%f_rhs(y,t) computes the vector RHS function f_rhs at t and y

% f_value is the value of the function at t, y

%

%NOTE: f_value must be a column vector

f_value=zeros(2,1);

%

y_value=y(1);

z_value=y(2);

f_value(1)=-4*y_value-z_value+exp(-t);

f_value(2)=y_value-2*z_value+sin(3*t);

%---------------------------------------------------------------------

81

Page 83: MATLAB TUTORIAL BASIC

Numerical Methods

Boundary Value Problems

ode45 cannot be applied directly to the solution of boundary value problems, such as

d2y

dx2= 0.7x2 y(0) = 1 y(10) = 5

However, such problems can be solved by using ode45 and a shooting method.

Shooting Methods

Given a value γ, the initial value problem

d2y

dx2= 0.7x2 y(0) = 1

dy

dx

x=0

= γ

has a solution y(x, γ) that depends on γ. We define

G (γ) = y(10, γ) − 5

It can be seen that solving the above boundary value problem value is equivalent to finding γ such

that y(10, γ) = 5 or G (γ) = 0.

82

Page 84: MATLAB TUTORIAL BASIC

Numerical Methods

Shooting Methods (continued)

To apply the simplest shooting method here, we guess a value for γ and use ode45 to compute a

solution at x = 10.

We look at how close we are to satisfying the actual condition at x = 10 and, based on this result,

we repeat the process with a new guess for the value of γ.

This process is continuously repeated until, hopefully, we eventually satisfy, to some desired accu-

racy, the required condition at x = 10.

With this simple approach, the number of guesses and, hence, the number of ode45 solutions that

are required may be considerable.

83

Page 85: MATLAB TUTORIAL BASIC

Numerical Methods

Example

We illustrate this simplest form of the shooting method by solving this boundary value problem. To

use ode45, the first step is to write the given differential equation as the first order system

dy

dx= f rhs(x, y)

where, for our example,

y =

y

u

u =dy

dxf rhs =

u

0.7x2

We specify the initial conditions in the form

y(0) =

[

y(0)u(0)

]

= yzero =

[

]

where we have to find the value of the constant γ to ensure that the actual boundary condition

y(10) = 5

is satisfied to a sufficient accuracy.

84

Page 86: MATLAB TUTORIAL BASIC

Numerical Methods

Example (continued)

To use ode45, we will write a function m–file (file example 10.m), with a sub–function (f rhs) to

define the right hand side of the differential equation to be solved.

function example_10

%example_10 example to illustrate the application of ode45

% to the solution of a boundary value problem

clc

clear

%set the range of x

xspan=[0 10]

%specify guessed value, gamma, for the value of u=dy/dx at x=0

gamma=input(’specify value for gamma = ’);

85

Page 87: MATLAB TUTORIAL BASIC

Numerical Methods

Example (continued)

%set the initial conditions

yzero=[1 gamma]

% solve the initial value problem

[xn,soln]=ode45(@f_rhs,xspan,yzero);

sol1n=soln(:,1);

%plot the variation of sol1n (=y) with x

plot(xn,sol1n,’o’)

%

xlabel(’x’)

ylabel(’numerical solution’)

%absolute error in the unsatisfied boundary condition at x=10 with this gamma

d=size(sol1n,1);

G=sol1n(d,1)-5;

fprintf(’\n absolute error in the boundary condition at x=10 is %g’,G)

86

Page 88: MATLAB TUTORIAL BASIC

Numerical Methods

Example (continued)

% sub-function

%

function [f_value]=f_rhs(x,y)

%f_rhs(x,y) computes the value the vector RHS function at x and y

% f_value is the value of this function at x, y

%NOTE: f_value must be a column vector

f_value=zeros(2,1);

%

y_value=y(1);

u_value=y(2);

f_value(1)=u_value;

f_value(2)=0.7*(x^2);

87

Page 89: MATLAB TUTORIAL BASIC

Numerical Methods

Example (continued)

If we use this m–file and specify the value

gamma=0, we obtain a solution for which the ab-

solute error in y(10) is 579.333. Repeating

this process many times, with different values

of gamma, we find that, when gamma=-57.9333,

we get an absolute error of 0.00033 in y(10).0 2 4 6 8 10

−300

−250

−200

−150

−100

−50

0

50

x

num

eric

al s

olut

ion,

y

The Shooting Method Revisited

Recall that, in a shooting method, for our example we are trying to find γ, such that the solution

y(x, γ) of the initial value problem

d2y

dx2= 0.7x2 y(0) = 0

dy

dx

x=0

= γ

is such that

G (γ) = y(10, γ) − 5 = 0

88

Page 90: MATLAB TUTORIAL BASIC

Numerical Methods

The Shooting Method Revisited (continued)

To determine the value of γ, it is better to replace the guesswork approach by a standard root finding

technique.

Unfortunately, we do not have an explicit expression for G (γ), but we can compute its value approx-

imately by solving the initial value problem.

In these circumstances, a suitable root finding technique is the secant method.

In this approach, suppose we have employed two values γn−1 and γn for γ, and that we have

computed the corresponding values

Gn−1 = G (γn−1) Gn = G (γn)

with ode45.

In this case, the secant method defines a new approximation for γ to be

γn+1 = γn − Gn(γn − γn−1)

(Gn − Gn−1)

89

Page 91: MATLAB TUTORIAL BASIC

Numerical Methods

The Shooting Method Revisited (continued)

A simple function m–file (file example 11.m) can be written to compute the new approximation γn+1,

when supplied with the values γn, γn−1, Gn and Gn−1.

Then, for example, this file can then be used in conjunction with the m–file example 10.m to reduce

the number of steps required in the solution of our boundary value problem.

To illustrate the process, suppose that we start with the value γ0 = 0. Using example 10.m to solve

our problem with ode45 gives G0 = 579.333. Repeating the process with the value γ1 = 1.0, we

find that ode45 gives G1 = 589.333.

Using these four values in the secant method formula produces the improved approximation γ2 =

−57.9333 for the root.

With this value for γ, ode45 produces a solution in which the absolute error in the satisfaction of the

boundary condition at x = 10 is G2 = 0.000333. If this error is unacceptable, the process may be

repeated until the desired level of accuracy is achieved.

90

Page 92: MATLAB TUTORIAL BASIC

Problems: 6

6.1 Water evaporates from most porous substances at a rate proportional to the moisture content of the substance.

Suppose that a towel is hung on a clothesline on a mild, windy day and that it loses 1/3 of its moisture in half an hour.

Show that the moisture content of the towel will certainly be less than 0.01 of its initial value after a time of 6 hours.

6.2 The variation of the population p(t) of a small city with time t in months is governed by the logistics equation

dp

dt= p(0.2 − 0.0000005p)

If the initial population is 5 000, plot the variation of p with t and estimate (a) the limiting population (i.e. the population

at large values of time t); (b) the time in years required for the population to reach one–half of its limiting value.

6.3 A cylindrical water tank with a cross–sectional area A (m2) is filled to an initial height h0 (m). At a given time, t = 0,

a ground level valve of cross-sectional area a (m2) is suddenly opened and the water starts to flow out of the tank. At

a later time t (sec), the water level in the tank is h (m) and the speed v of the outflow is such that v2 = 2gh (m/sec),

where g is the acceleration due to gravity. In addition, at time t = 0, water is poured into the top of the tank at a constant

rate f (m3/sec). Obtain the differential equation that governs the variation of h with t.

If f = 0, A = 20, a = 0.01, g = 9.81 and h0 = 5, use ode45 to plot the variation of h with t and use your plot to

estimate the time, te, needed to empty the tank.

91

Page 93: MATLAB TUTORIAL BASIC

Problems: 6

6.4 Two tanks 1 and 2 are connected by a single pipe. Water flows from tank 1 to tank 2 through this pipe at a rate

2y (litres/min), where y(t) is the volume of water in tank 1 at time t. At the same time, water flows out of tank 2 at a

constant rate of 20 (litres/min) and is pumped into tank 1 at a rate 5(25 − z) (litres/min), where z(t) is the volume of

water in tank 2 at time t. If, initially, tank 2 is empty and tank 1 contains 18 litres of water, plot the variation of y and z

for 0 ≤ t ≤ 10 (min). Estimate the volume of water in each tank for large values of t.

6.5 The equation governing the unforced damped vibration y(t) of a certain spring/mass system is given to be governed

by the equation

md2y

dt2+ c

dy

dt+ ky = 0

and the initial conditions

y(0) = 0.25 mdy

dt

t=0

= 20 m/sec

If m = 3 (kg) and k = 3× 102 (N/m), plot, on the same figure, the variation of y for 0 ≤ t ≤ 4 (s) for the cases (a) c=6

(Nsec/m) (b) c=60 (Nsec/m) (c) c=600 (Nsec/m).

When this system is subjected to a certain applied external force, the governing differential equation is given to be

md2y

dt2+ c

dy

dt+ ky = 50sin(10t)

Repeat the above computations for this case and produce a new plot showing the variation of y with t.

92

Page 94: MATLAB TUTORIAL BASIC

Problems: 6

6.6 Consider the system of 3 springs and 2 masses, A and B, shown in the figure. The natural length of each spring

is 1 (m) and the stiffness (in N/m) of each spring is shown in the figure. The masses A and B are both of mass 1 (kg)

and, for the purposes of this example, the masses may be regarded as points.

spring 1 spring 2 spring 3k =6 k =2 k =31 2 3

x

y

1 1 1

A B

t=0

Configuration at later time

Initial configuration at time

t

At a certain time, t = 0, the system is at rest in its equilibrium position and mass A is given a positive velocity of 0.5

(m/sec). Derive the governing equations in the form of a first order equation system and plot the locations x(t) and y(t)

of the two masses as a function of t for 0 ≤ t ≤ 10 (sec).

If the system is initially at rest, in its equilibrium position, with zero velocity, and assuming the springs are infinitely

compressible, show that the masses will collide if an external force F = sin3t is applied to the mass A for t ≥ 0.

Estimate the time at which this collision will occur.

93

Page 95: MATLAB TUTORIAL BASIC

Problems: 6

6.7 The distribution of the axial velocity component in a certain incompressible viscous fluid, flowing between two parallel

porous walls with suction, is described, in dimensionless form, by the solution of the differential equation

10dy

dx= 5 + 2

d2y

dx2

and the boundary conditions

y(0) = 0 y(1) = 0

Solve this problem using ode45 and plot the distribution of y for 0 ≤ x ≤ 1.

6.8 A company is constructing a new bungee jumping facility. The height of the platform will be 80 (m) above the ground

and it is intended to use an elastic cord of unstretched length 30 (m). The company has access to three different types

of elastic cord, with elastic constants k equal to 5 (N/m), 40 (N/m) and 100 (N/m) respectively. An individual will not be

allowed to jump if his/her weight exceeds 14 stone. If g = 9.81 (m/sec2), and if the air resistance experienced by the

jumper at any instant is equal to a1u+ a2u2, where u is the instantaneous speed of the jumper, show that the distance,

y(t), of a jumper of mass m (kg) from the platform at any time, t (sec), may be found by solving the initial value problem

md2y

dt2+ a1

dy

dt+ a2

dy

dt

dy

dt

∣= mg − F (t) y(0) = 0

dy

dt

t=0

= 0

where F is the force provided by the elastic cord. If, based upon the results of experimental observations, a1 = 1

(kg/sec) and a2 = 1 (kg/m), determine which rope the company should use, if they are to be certain that no jumper will

get closer than 10 (m) to the ground.

94

Page 96: MATLAB TUTORIAL BASIC

Problems: 6

6.9 The engineering analysis of a certain flow system leads to the differential equation

d2y

dx2− y = x

and the boundary conditions

y(0) = 1 y(5) = 2.8

Use a shooting method to obtain a solution y(x) in which the absolute error in the value of y(5) is less than 1.0×10−4

in absolute value. The secant method should be used to reduce the number of iterations required to produce the

solution.

Plot the solution y for 0 ≤ x ≤ 5 and print out the value of (dy/dx)x=0.

95

Page 97: MATLAB TUTORIAL BASIC

Assignments 2 and 3

Advice on Preparing m–files for Assignments 2 and 3

The following steps should be followed when preparing your m–files for assessment:

1. create a function m–file, EG399 studentnumber assignmentnumber.m, in your working directory

to contain the MATLAB commands necessary to produce the solution to the problem;

2. continue editing and running the m–file until you are confident that it contains the commands

necessary to solve the problem without user interaction;

3. add comments to your m–file which explain the method being used to solve the problem and to

interpret the results. Your file should contain sufficient comments to enable the steps being followed,

and the results obtained, to be clearly understood by someone who is not familiar with the problem.

Marking Assignments 2 and 3

For each Assignment, marks will be awarded for (a) the quality of the submission (16 marks); (b)

the accuracy of the results produced (20 marks); the MATLAB techniques employed (4 marks)

96

Page 98: MATLAB TUTORIAL BASIC

Assignment 2

Advice on Preparing Assignment 2 for Assessment

The following steps should be followed when preparing your solution to Assignment 2 for assess-

ment:

1. Create a document that contains your m–file and your solution to the given problem;

2. Add a front page to your document which clearly states the course code (EG–399), the assign-

ment number, your name and your student number;

3. Add to your front page the signed statement “Apart from where referenced, I confirm that I have

not received help from, or given help to, anyone else in constructing the solution to this assignment;

4. Hand your assignment to me personally at the designated lecture in week 22.

Note that the problem is defined in terms of data that is based upon your student number, which is

taken in the form ABCDEF . Hence, if your student number is 971254, you should take A = 9,

B = 7, C = 1, etc.

97

Page 99: MATLAB TUTORIAL BASIC

Assignment Problem 2

Assignment 2

The laminar boundary layer flow of an incompressible viscous fluid on a certain surface may be described in terms of

the solution of the Falkner–Skan equation

d3y

dx3+

(

0.1D + 1

2

)

yd2y

dx2+ 0.1E

[

1 −(

dy

dx

)2]

= 0

subject to the boundary conditions

y(0) = 0dy

dx

x=0

= 0dy

dx

x=∞= 1

Use a shooting method to obtain a solution, when the condition at infinity is imposed at x = 2F . For your solution

1. print out the absolute value of the error in the given boundary condition at x = ∞ (you should ensure that this is

less than 10−5);

2. print out the value of (d2y/dx2)x=0;

3. plot the distribution of dy/dx for 0 ≤ x ≤ 2F .

NOTE: More marks will be obtained if your m–file runs without user intervention i.e. if the secant method is automatically

included as part of the solution process.

98

Page 100: MATLAB TUTORIAL BASIC

Partial Differential Equations

Second Order Partial Differential Equations

Many practical engineering problems are governed by the solution of second order partial differential

equations. Let t denote time and x and y cartesian spatial coordinates.

The solution u(x, y) of steady heat conduction problems in two space dimensions, or of problems

in electrostatics or ideal fluid flow, satisfies Laplace’s equation

∂2u

∂x2+

∂2u

∂y2= 0 or div grad u = 0 or ∇2u = 0

The solution u(x, y, t) of unsteady heat conduction problems in two space dimensions, or of prob-

lems in water seepage, satisfies the diffusion equation

∂u

∂t=

∂2u

∂x2+

∂2u

∂y2or

∂u

∂t= div grad u or

∂u

∂t= ∇2u

The solution u(x, y, t) of unsteady wave propagation problems in two space dimensions satisfies

the wave equation

∂2u

∂t2=

∂2u

∂x2+

∂2u

∂y2or

∂2u

∂t2= div grad u or

∂2u

∂t2= ∇2u

99

Page 101: MATLAB TUTORIAL BASIC

Partial Differential Equations

Classification of Second Order Partial Differential Equations

Consider second order partial differential equations involving two independent variables e.g. x and

y for steady heat conduction and x and t for unsteady heat conduction or wave propagation.

In this case, the general form of a quasi–linear second order partial differential equation will be

a∂2u

∂x2+ b

∂2u

∂x∂y+ c

∂2u

∂y2= d

where a, b, c and d may be constants or functions of x, y, u and its first derivatives.

These equations are classified as follows:

Equation Type If Example Problem Type

elliptic b2 < 4ac Laplace equation boundary value

parabolic b2 = 4ac diffusion equation initial/boundary value

hyperbolic b2 > 4ac wave equation initial/boundary value

100

Page 102: MATLAB TUTORIAL BASIC

Partial Differential Equations

Solution of Second Order Partial Differential Equations

Generally, the solution of a partial differential equation is required within a region surrounded by

a boundary. Analytical solutions are only possible when the boundary shape is very simple (e.g.

a rectangle or a circle) and the associated conditions are also very simple. In these cases, the

analytical solution is normally obtained in the form of an infinite series.

This means that approximate numerical techniques are normally applied in the solution of practical

problems. We will start by looking at some simple finite difference methods of solution.

A Finite Difference Method for Laplace’s Equation

Problems governed by Laplace’s equation

∂2u

∂x2+

∂2u

∂y2= 0

will be boundary value problems and the boundary conditions will be of Dirichlet form, i.e. the value

of u is specified on the boundary, or Neumann form, i.e. the value of the normal derivative of u is

specified on the boundary.

In a given problem, both types of conditions may appear.

101

Page 103: MATLAB TUTORIAL BASIC

Partial Differential Equations

A Finite Difference Method for Laplace’s Equation (continued)

Suppose we need to solve a problem of steady heat conduction in a square shaped region. Suppose

that the boundary conditions are of Dirichlet type, so that the value of the temperature u is known

everywhere on the boundary.

Suppose the square has side length L and is defined by the region 0 ≤ x ≤ L,0 ≤ y ≤ L. Cover

this square by a finite difference grid i.e.

1. mark off a set of K points xk = (k − 1)∆x, k = 1,2, . . . , K such that x1 = 0 and xK = L;

2. mark off a set of J points yj = (j − 1)∆y, k = 1,2, . . . , J such that y1 = 0 and yJ = L;

3. form the grid by drawing a line parallel to the y axis through each point (xk,0) and a line

parallel to the x axis through each point (0, yj).

Nodes are the points at which these grid lines intersect. A typical interior node is located at the

point (xk, yj). We use the notation

u(xk, yj) = uj,k

102

Page 104: MATLAB TUTORIAL BASIC

Partial Differential Equations

A Finite Difference Method for Laplace’s Equation (continued)

In the finite difference method, we attempt to find approximations to these nodal values uj,k. To do

this, we evaluate the differential equation at a typical interior point (xk, yj) to get

∂2u

∂x2

j,k

+∂2u

∂y2

j,k

= 0

and use the finite difference approximations

∂2u

∂x2

j,k

≈ uj,k+1 − 2uj,k + uj,k−1

∆x2

∂2u

∂y2

j,k

≈ uj+1,k − 2uj,k + uj−1,k

∆y2

to obtain the approximation

1

∆x2uj,k+1 +

1

∆y2uj+1,k +

1

∆x2uj,k−1 +

1

∆y2uj−1,k − 2

(

1

∆x2+

1

∆y2

)

uj,k = 0

Using this approximation at each interior node gives a set of (J − 2) × (K − 2) equations in

(J − 2) × (K − 2) unknowns, when the boundary conditions are inserted. Note that the error in

the above approximations gets smaller as ∆x and ∆y get smaller.

This set of linear equations may be solved using matrix methods, such as direct inversion or iterative

techniques.

103

Page 105: MATLAB TUTORIAL BASIC

Partial Differential Equations

Example

Obtain the steady state distribution of temperature in the square region 0 ≤ x, y ≤ 4, subject to the

boundary conditions

u(0, y) = 25y u(4, y) = 0 u(x,0) = 0 u(x,4) = 100 − 25x

Suppose we use ∆x = ∆y = 1, so that J = K = 5. At the boundary nodes, this means that

uj,1 = 25(j − 1)∆y uj,5 = 0 u1,k = 0 u5,k = 100 − 25(k − 1)∆x 1 ≤ j, k ≤ 5

and the finite difference approximation to Laplace’s equation becomes

uj+1,k + uj,k+1 + uj−1,k + uj,k−1 − 4uj,k = 0 2 ≤ j, k ≤ 4

This is a set of 3 × 3 = 9 linear equations which, upon insertion of the boundary conditions, can

be written in the form

Au = f

and solved directly by Gaussian elimination. Although this is practicable for this problem, this ap-

proach becomes very expensive as the size of ∆x and ∆y is reduced.

104

Page 106: MATLAB TUTORIAL BASIC

Partial Differential Equations

Example (continued)

An alternative is to use an iterative solution technique e.g. we can attempt to solve our equation set

by using the Jacobi iteration scheme

uiter+1j,k =

1

4

(

uiterj+1,k + uiter

j,k+1 + uiterj−1,k + uiter

j,k−1

)

2 ≤ j, k ≤ 4 iter = 0,1,2, . . .

To start this iterative process, we must guess values u0j,k for the temperature distribution at every

node.

The iterative process is continued until convergence i.e. until we reach a value of iter such that

maxj,k

∣uiter+1

j,k − uiterj,k

∣< ǫ

where ǫ is a user–specified tolerance level.

A possible MATLAB implementation of this procedure would be (file example 12.m)

function example_12

%example_12 finite difference solution of Laplace’s equation

105

Page 107: MATLAB TUTORIAL BASIC

Partial Differential Equations

Example (continued)

% temperature distribution u(x,y)

% on a square region of side length 4

% defined by 0 < x,y < 4

% equal grid spacing Delta x= Delta y

% Jacobi iteration Dirichlet boundary conditions

clear

clc

%specify side length L

%

L=4;

%specify N: number of grid points in x direction

N=input(’\n number of grid points in x direction =’);

%construct nodal points

deltax=L/(N-1);

deltay=deltax;

106

Page 108: MATLAB TUTORIAL BASIC

Partial Differential Equations

Example (continued)

for k=1:N

x(k)=(k-1)*deltax;

end

for j=1:N

y(j)=(j-1)*deltay;

end

%initial guess for the temperature distribution: uold(i,j)

uold=zeros(N,N);

%set Dirichlet boundary conditions

% u(0,y)=25*y u(4,y)=0 u(x,0)=0 u(x,4)=100-25*x

for j=1:N

uold(j,1)=25*y(j);

uold(j,N)=0;

end

107

Page 109: MATLAB TUTORIAL BASIC

Partial Differential Equations

Example (continued)

for k=1:N

uold(1,k)=0;

uold(N,k)=100-25*x(k);

end

%specify iteration convergence value

epsilon=1e-01;

%set max number of allowed iterations

iter_max=1000;

%Jacobi iteration

for iter=1:iter_max

%interior nodes only

for j=2:N-1

for k=2:N-1

unew(j,k)=(1/4)*(uold(j+1,k)+uold(j-1,k)+uold(j,k+1)+uold(j,k-1));

end

end

108

Page 110: MATLAB TUTORIAL BASIC

Partial Differential Equations

Example (continued)

%set boundary values

for k=1:N

unew(k,1)=25*y(k);unew(k,N)=0;unew(1,k)=0;

unew(N,k)=100-25*x(k);

end

%obtain the max change at any interior nodal point

max_diff=0;

for j=2:N-1

for k=2:N-1

change=abs(unew(j,k)-uold(j,k));

if change>max_diff

max_diff=change;

end

end

end

109

Page 111: MATLAB TUTORIAL BASIC

Partial Differential Equations

Example (continued)

%save maximum change for plotting convergence

max(iter)=max_diff;

icount(iter)=iter;

%reset the solution values for the next iteration

for j=1:N

for k=1:N

uold(j,k)=unew(j,k);

end

end

%======================================================================

%stop the process if max_diff <= epsilon

%======================================================================

if max_diff <= epsilon

break

end

end

110

Page 112: MATLAB TUTORIAL BASIC

Partial Differential Equations

Example (continued)

%converged solution

unew

%plot convergence curve

fprintf(’\n Jacobi iteration converged in %g steps\n’,iteration)

plot(icount,max) xlabel(’iteration number’) ylabel(’max change’)

pause

%plot contours

surf(x,y,unew)

xlabel(’x’)

ylabel(’y’)

zlabel(’temperature’)

0 2 4 6 8 10 12 140

5

10

15

20

25

30

35

40

iteration number

max

nod

al c

hang

e

convergence of Jacobi iteration

01

23

4

0

1

2

3

40

20

40

60

80

100

xy

tem

pera

ture

contour plot of the solution111

Page 113: MATLAB TUTORIAL BASIC

Partial Differential Equations

A Finite Difference Method for the Diffusion Equation

Problems governed by the diffusion equation

∂u

∂t=

∂2u

∂x2

will be initial/boundary value problems with a solution domain of the form

0 ≤ x ≤ L t > 0

The value of u will be specified for 0 ≤ x ≤ L at time t = 0 and this will be the initial condition.

Dirichlet or Neumann boundary conditions must be supplied at x = 0 and x = L for all time t > 0.

Suppose we want to find the transient variation of temperature u(x, t) in the one dimensional region

0 ≤ x ≤ 10. The region is at the uniform temperature of 20o when, suddenly, the temperature at

end x = 0 is increased to 100o and held constant at that value.

Decide upon a final time of interest T and, using the points xk = (k − 1)∆x, k = 1,2, . . . , K and

tn = (n − 1)∆t, n = 1,2, . . . , N , construct a finite difference grid on the region 0 ≤ x ≤ 10,

0 ≤ t ≤ T . We use the notation

u(xk, tn) = unk

112

Page 114: MATLAB TUTORIAL BASIC

Partial Differential Equations

A Finite Difference Method for the Diffusion Equation (continued)

To find approximations to these nodal values, unk , we evaluate the differential equation at a typical

interior point (xk, tn) to get

∂u

∂t

n

k

=∂2u

∂x2

n

k

and use the finite difference approximations

∂2u

∂x2

n

k

≈un

k+1 − 2unk + un

k−1

∆x2

∂u

∂t

n

k

≈ un+1k − un

k

∆t

to obtain the approximation

un+1k = un

k +∆t

∆x2

(

unk+1 − 2un

k + unk−1

)

Thus, provided the temperature is known at all nodal points at time tn, this explicit formula enables

the determination of the temperature at all nodal points at time tn+1.

As the initial condition defines the temperature at all nodal points at time t1 = 0, we can compute

the solution by stepping forward in time, firstly obtaining the solution at time t2, then at time t3, and

so on, until we reach the final time T .

113

Page 115: MATLAB TUTORIAL BASIC

Partial Differential Equations

A Finite Difference Method for the Diffusion Equation (continued)

The solution gets better as ∆x and ∆t become smaller. Note that, when ∆x has been chosen,

∆t can not be assigned an arbitrary value with this procedure. Stability considerations imply that

we must employ a value for ∆t which is such that

α =∆t

∆x2≤ 1

2

A possible MATLAB implementation of this procedure can be found in file example 13.m.

0

2

4

6

8

100

5

10

15

2020

40

60

80

100

xt

tem

pera

ture

contour plot of the solution

0 ≤ t ≤ 20 α = 0.2

K = 11 N = 100

114

Page 116: MATLAB TUTORIAL BASIC

Assignment 3

Advice on Preparing Assignment 3 for Assessment

The following steps should be followed when preparing your solution to Assignment 3 for assess-

ment:

1. Create a document that contains your m–file and your solution to the given problem;

2. Add a front page to your document which clearly states the course code (EG–399), the assign-

ment number, your name and your student number;

3. Add to your front page the signed statement “Apart from where referenced, I confirm that I have

not received help from, or given help to, anyone else in constructing the solution to this assignment;

4. Hand your assignment to me personally at the designated lecture in week 24.

Note that the problem is defined in terms of data that is based upon your student number, which is

taken in the form ABCDEF . Hence, if your student number is 971254, you should take A = 9,

B = 7, C = 1, etc.

115

Page 117: MATLAB TUTORIAL BASIC

Assignment Problem 3

Assignment 3

An elastic string is fixed at the points x = 0 and x = ℓ = 1 + A. At time t = 0, the string is held with a displacement

y = (1 + B) sin

(

2πx

)

for 0 ≤ x ≤ ℓ

and its velocity∂y

∂t= 0 for 0 ≤ x ≤ ℓ

The string is then released and the subsequent displacement is governed by the solution of the wave equation

(1 + C)∂2y

∂t2= (1 + D)

∂2y

∂x2for 0 < x < ℓ and 0 < t ≤ τ

(a) Using standard central difference approximations for both the second order time and space derivatives, derive an

explicit finite difference procedure for the solution of this problem. For this process, use a mesh with typical nodal

coordinate (xj, tn) = ((j − 1)∆x, (n − 1)∆t), for j = 1,2, · · · , J + 1;n = 1,2, · · · , N + 1, and let ynj denote

y(xj, tn). Here, J∆x = ℓ and N∆t = τ . This scheme is known to be stable when

λ2 =(1 + D)∆t2

(1 + C)∆x2≤ 1

(b) Note that this scheme requires knowledge of y1j and y2

j before it can be used in practice. Derive a formula for the

approximate computation of y2j , using a Taylor expansion in time (correct to second order), the wave equation itself and

the standard central difference approximation for the second order spatial derivative.

(c) Use the resulting procedure, with J = (10 + E), λ = 1 and N = (2 + F )× 10.

(d) Plot the displacement of the string at time t = τ and produce a contour plot of the solution for 0 ≤ x ≤ ℓ; 0 ≤ t ≤ τ .

116

Page 118: MATLAB TUTORIAL BASIC

PDE Toolbox: Basics

The PDE Toolbox

The PDE toolbox is included within MATLAB and enables the solution of certain partial differential

equations in two spatial dimensions and time. The solutions are obtained by the finite element

method.

The PDE toolbox provides the user with the ability to:

1. completely define a problem, in terms of the differential equation, the region over which the

solution is required and the boundary conditions;

2. solve the problem by automatically generating a mesh, approximating the differential equation

and solving the finite element equations;

3. visualize the results.

The process can be undertaken via graphical user interface (GUI), which may be accesses by typing

pdetool at the >> prompt in the MATLAB command window.

A solution can be obtained within the GUI, without a detailed knowledge of the mathematics behind

the differential equation, the finite element approximation, or even MATLAB!!

117

Page 119: MATLAB TUTORIAL BASIC

PDE Toolbox: Basics

Differential Equations Included in the Toolbox

For our purposes, we can view the PDE toolbox as a facility that we can use to solve

1. the elliptic equation

−div · (cgrad u) + au = f or − ∂

∂x

(

c∂u

∂x

)

− ∂

∂y

(

c∂u

∂y

)

+ au = f

with defined boundary conditions;

2. the parabolic equation

d∂u

∂t− div · (cgradu) + au = f or d

∂u

∂t− ∂

∂x

(

c∂u

∂x

)

− ∂

∂y

(

c∂u

∂y

)

+ au = f

with defined initial and boundary conditions;

3. the hyperbolic equation

d∂2u

∂2t− div · (cgradu) + au = f or d

∂2u

∂2t− ∂

∂x

(

c∂u

∂x

)

− ∂

∂y

(

c∂u

∂y

)

+ au = f

with defined initial and boundary conditions.

118

Page 120: MATLAB TUTORIAL BASIC

PDE Toolbox: Basics

Define a Problem

The simplest way to define a problem is to use the pdetool command to initiate the GUI.

The problem is set up using:

1. DRAW mode:

to define the problem geometry, using solid geometry modelling. A set of solid objects—

rectangle, circle, ellipse and polygon—is provided. Combination operations can be performed

using set algebra;

2. BOUNDARY mode:

to specify the boundary conditions. Different types of boundary conditions may be applied on

different boundary segments;

3. PDE mode:

to specify the type of differential equation and define the appropriate coefficients.

119

Page 121: MATLAB TUTORIAL BASIC

PDE Toolbox: Basics

Solve a Problem

The problem can be solved from the GUI using:

1. MESH mode:

to generate and plot the mesh. An unstructured mesh of triangles is employed;

2. SOLVE mode:

either

to solve an elliptic boundary value problem;

or

to define initial values, specify the times at which the solution is required and solve a

parabolic or a hyperbolic problem.

After solving, you can return to MESH mode to refine the mesh and repeat the solution process.

An automatic adaptive mesh refinement procedure is provided, which tries to find the best mesh

that produces an accurate solution.

120

Page 122: MATLAB TUTORIAL BASIC

PDE Toolbox: Basics

Visualize the Solution

The GUI provides a range of visualization functions. These enable the form of the computed solution

to be interpreted using:

PLOT mode:

1. colour contours for scalar and vector fields;

2. arrow plots for vector fields;

3. mesh visualisation;

4. animation of the solution for parabolic and hyperbolic problems.

121

Page 123: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 1

Example 1

To illustrate the use of the PDE toolbox, consider the solution of the following elliptic boundary value

problem:

1. The partial differential equation

∂2u

∂x2+

∂2u

∂y2= −40 or − div · (gradu) = 40

2. The region Ω where the solution is required

Ω = −0.5 ≤ x, y ≤ 0.5

3. The condition to be imposed on the boundary ∂Ω of Ω

Dirichlet type: u = 1.0 on ∂Ω

Application areas for this sort of problem include heat conduction, ideal fluid flow and elastic mem-

brane deformation.

122

Page 124: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 1

Step 1: Open the GUI

Type pdetool at the MATLAB prompt in the command window.

When the GUI appears, turn on the grid by selecting Grid from the Options menu.

123

Page 125: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 1

Step 2: Define the Region Ω

Select the Rectangle/Square object from the Draw menu. Press the plain rectangle button and place

the cursor at one corner of Ω.

Click–and–drag, using the left mouse button, to create the square region Ω. This is assigned the

label R1.

124

Page 126: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 1

Step 3: Define the Boundary Conditions on ∂Ω

Select Boundary Mode from the Boundary menu. The boundary segments are then indicated by

colored lines with arrows.

The colour indicates the type of boundary condition being applied. The default condition is Dirichlet

type, which is coloured red.

125

Page 127: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 1

Step 3: Define the Boundary Conditions on ∂Ω (continued)

Select Specify Boundary Conditions from the Boundary menu. The Boundary Condition dialog

box appears. Select the Dirichlet condition type and, to impose the required condition u = 1 on

∂Ω for this example, enter 1 for h and 1.0 for r.

Boundary conditions can be applied/changed by clicking on one boundary segment, by shift–clicking

to select multiple segments, or by using the Edit menu and Select All to select all segments.

Selected segments are coloured in black.

126

Page 128: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 1

Step 4: Define the Partial Differential Equation

Select PDE Specification from the PDE menu. The PDE Specification dialog box will appear.

For this example, select the PDE type to be elliptic and define the relevant equation by setting

c = 1, a = 0 and f = 40.

127

Page 129: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 1

Step 5: Generate an Initial Mesh of Triangles

The region Ω is represented by a mesh of triangles. The mesh is created and displayed by selecting

the option Initialize Mesh from the Mesh menu.

128

Page 130: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 1

Step 6: Generate a Refined Mesh of Triangles

If the initial mesh is regarded as being too coarse, it can be refined by selecting the Refine Mesh

option from the Mesh menu.

The quality of the mesh can be improved by using the Jiggle Mesh option.

129

Page 131: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 1

Step 7: Solve the Problem

Select Solve PDE from the Solve menu to solve the problem that has been defined.

The solution is displayed in the form of a plot, using interpolated colouring and a linear colour map.

130

Page 132: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 1

Step 8: Visualise the Solution

Plot Selection: other plotting modes can be selected to help in visualising the solution. Select

Parameters from the Plot menu to access the Plot Selection dialog box.

Select both Color and Height.

Select both interpolated shading and continuous plot style.

Select Show mesh.

Press the Plot button to obtain the plot.

131

Page 133: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 1

Step 8: Visualise the Solution (continued)

The plot can be rotated using the mouse and can be viewed from different angles.

132

Page 134: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 2

Example 2

The second example again involves the solution of an elliptic equation, but this time the domain Ω,

and the boundary conditions to be imposed on the boundary ∂Ω of Ω, are more complicated.

1. The partial differential equation remains the same:

∂2u

∂x2+

∂2u

∂y2= −40 or − div · (gradu) = 40

2. The region Ω where the solution is required is shown on the next page and consists of a region

formed by the union of a square and four circles;

3. The conditions to be imposed on the boundary ∂Ω of Ω:

Dirichlet type: u = 1 on the boundary of the square

Neumann type: n · gradu = ∂u/∂n = −1 on the boundary of the circles.

133

Page 135: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 2

Defining the Domain Ω:

Draw the square R1 defined by −0.5 ≤ x, y ≤ 0.5 as before. Draw the circles C1, E1, E2, E3, as

illustrated, with each circle being centred at a corner of the square and of radius 0.2. The region Ω

is defined by the set formula Ω = R1 + C1 + E1 + E2 + E3.

134

Page 136: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 2

Setting Boundary Conditions:

Select Boundary Mode from the Boundary menu. The boundaries ∂Ω of Ω are shown in red. Sub–

domain boundaries, i.e. boundaries of the square and circles which now lie inside Ω, are shown in

gray.

135

Page 137: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 2

Setting Boundary Conditions (continued):

Select Remove All Subdomain Borders from the Boundary menu and the sub–domain boundaries

are removed. Note that segments along which Dirichlet type conditions are defined are coloured

red, while blue is used for the segments which are defined to be subjected to Neumann conditions.

Segments for which a mixed Dirichlet/Neumann condition is defined are shown in green.

136

Page 138: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 2

Setting Boundary Conditions (continued):

Initially, specify the boundary conditions on all segments to be of Dirichlet type and define the values

h = 1, r = 1.0 required to be imposed on the sides of the square. Then, use Shift and click to

select all the boundary segments that consist of circular arcs. These segments are coloured black

and are indicated with arrows, as shown in the figure.

Double clicking anywhere on these boundary segments opens the Boundary Conditions dialog

box. Choose the Neumann condition and obtain the required boundary condition by setting q = 0

and g = −1.

137

Page 139: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 2

Defining the Partial Differential Equation:

Select the elliptic equation option and specify the parameters as before.

Mesh Generation:

Generate a triangular mesh. Select the refinement option and jiggle the mesh once or twice. A

mesh constructed in this fashion is shown in the figure.

138

Page 140: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 2

Solving the Equation and Visualization of the Solution:

Solve the partial differential equation as before and plot the coloured contours of the solution.

139

Page 141: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 2

Solution Visualization:

A 3D representation of the solution may be obtained by selecting the visualization parameters in the

manner described previously.

140

Page 142: MATLAB TUTORIAL BASIC

PDE Toolbox: Example 2

Extracting Numerical Data:

Although contour plots may be used to gain an understanding of the nature of the solution, the

engineer is frequently interested in obtaining specific information about the solution e.g. the actual

value of the solution at specified locations.

Upon completion of the solution process, the value, uvalue, of the computed solution u at the point

with coordinates (a, b) may be determined by

1. selecting Export Mesh from the Mesh menu and clicking the OK button;

2. selecting Export Solution from the Solve menu and clicking the OK button;

3. typing [u value,tri num]=tri2grid(p,t,u,a,b) in the command window.

The value of u at (a, b) will be displayed, together with the number of the triangle in the mesh that

contains the point (a, b).

141

Page 143: MATLAB TUTORIAL BASIC

Problems: 7

7.1 A certain elastic membrane covers the region Ω formed by the union of a rectangle, of side lengths 2 and 0.75,

and a semi–circle of diameter 2. Under certain loading conditions, the deflection u(x, y) of the membrane satisfies the

differential equation

−div · (gradu) = 10 in Ω

and the Dirichlet condition u = 0 at the boundary ∂Ω of ω. Use the PDE toolbox to obtain plots of an approximation to

the deflection distribution.

7.2 The distribution of temperature u(x, y) in a rectangular plate satisfies the differential equation

−div · (gradu) = 0 0 ≤ x ≤ 3 0 ≤ y ≤ 1

The points a, b, c, d, e, f are located at (0,0), (1,0), (3,0), (3,1), (1,1), (0,1) respectively, as illustrated in the figure,

and the plate is subjected to the Dirichlet condition u = 0 on the edge af , the Dirichlet condition u = 100 on the edges

dc, ed, bc and the Neumann condition ∂u/∂n = 0 on the thermally insulated edges fe, ab.

a b c

def

Use the PDE toolbox to obtain a plot of an approximate representation of the temperature distribution in the plate and

determine approximations to the value of the temperature at the points (0.5,0.5) and (2,0.5).

142