You are on page 1of 85

Selected Solutions for Exercises in

Numerical Methods with Matlab:


Implementations and Applications
Gerald W. Recktenwald
Chapter 2
Interactive Computing with Matlab

The following pages contain solutions to selected end-of-chapter Exercises


from the book Numerical Methods with Matlab: Implementations and
c 2000, Prentice-Hall, Upper
Applications, by Gerald W. Recktenwald, 
c 2000 Gerald W. Recktenwald. The
Saddle River, NJ. The solutions are 
PDF version of the solutions may be downloaded or stored or printed only
for noncommercial, educational use. Repackaging and sale of these solutions
in any form, without the written consent of the author, is prohibited.
The latest version of this PDF le, along with other supplemental material
for the book, can be found at www.prenhall.com/recktenwald.

Interactive Computing with Matlab

21 Use the lookfor command to search for functions associated with the string max. From
the list of functions returned, use the help facility to determine the function that nds the
maximum of all entries in a matrix. Apply this function to nd the largest entry in the
following matrices:

1 5 2
sin(1) sin(5) sin(2)
4 9 ;
sin(4) sin(9)
A= 3
B = sin(3)
7 2
6
sin(7) sin(2)
sin(6)
Solution: Given a vector as input, the max function returns the maximum element. Given
a matrix as input, the max function returns a row vector containing the maximum element in
each column of the matrix. To nd the maximum element in the matrix, apply max twice.
Notice that the arguments of the sine function in matrix B are the elements of A.
>> lookfor max

% ... returns long list of built-in functions

>> help max

% ... returns documentation on max function

>> A = [ 1 -5 -2; 3 4 -9; -7 2 6];


>> max(max(A))
ans =
6
>> B = sin(A)
B =
0.8415
0.9589
0.1411
-0.7568
-0.6570
0.9093
>> max(max(B))
ans =
0.9589

-0.9093
-0.4121
-0.2794

25 Use the linspace function to create vectors identical to those obtained with the statements
that follow. Use multiple statements where necessary. (Use Matlabs built-in norm function
to test whether two vectors are equal without printing the elements.)
(a) x = 0:10
(b) x = 0:0.2:10
(c) x = -12:12
(d) x = 10:-1:1
Partial Solution: The table below gives equivalent linspace expressions for the colon notation expressions in the rst column. To test whether these statements are correct, enter the
commands to create x and y, and then compute norm(x-y).
colon notation
x = 0:10
x = -12:12

linspace
y = linspace(0,10,11)
y = linspace(-12,12,25)

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 2: Interactive Computing with Matlab



29 Given the row vector x = 10

9 8


7 and column vector

1
2

y=
3
4

write at least two dierent ways to compute the row vector z dened by zi = xi yi . Your
answers should take only one assignment operation. Do not, for example, explicitly write out
equations for all of the elements of z.
Partial Solution: One of the less obvious ways to create z is z = ( x - y ).
215 Use the eye and fliprl functions to create the matrix

0 0 1
E = 0 1 0
1 0 0
Does the same trick work with flipud?
Typographical Error: fliprl should be fliplr.
Solution: E = fliplr(eye(3)). Yes, E = flipud(eye(3)) also works.
224 Plot sin versus for 60 points in the interval 0 2. Connect the points with a dashed
line and label the points with open circles. (Hint: Users of Matlab version 4 will need to
plot the data twice in order to combine the symbol and line plots.)
Partial Solution: The correct Matlab statements produce the following plot
1

0.8

0.6

0.4

sin()

0.2

-0.2

-0.4

Plot of solution to
Exercise 224.

-0.6

-0.8

-1

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Interactive Computing with Matlab

225 Create a plot of the response of a second-order system with = 0, = 0.3, and = 0.9.
Use the formula in Example 2.2, and combine the response curves for all three values on the
same plot. Label the axes and identify the curves with a legend.
Partial Solution: The correct Matlab statements produce the following plot
2.5
zeta = 0.10
zeta = 0.30
zeta = 0.90

Displacement (arbitrary units)

1.5

Plot of solution to
Exercise 225.

0.5

0.02

0.04

0.06

0.08
0.1
0.12
Time (arbitrary units)

0.14

0.16

0.18

0.2

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 2: Interactive Computing with Matlab

230 Data in the table that follows were obtained from an experiment in which the theoretical
model is y = 5x exp(3x). The xm and ym values were measured, and the y values were
obtained from an uncertainty analysis. Use the built-in errorbar function to create a plot of
the experimental data with error bars. Use the hold on and plot functions to overlay a plot
of the measured data with the theoretical model. The data are stored in the xydy.dat le in
the data directory of the NMM toolbox.
xm
ym
y

0.010
0.102
0.0053

0.223
0.620
0.0490

0.507
0.582
0.0671

0.740
0.409
0.0080

1.010
0.312
0.0383

1.220
0.187
0.0067

1.530
0.122
0.0417

1.742
0.081
0.0687

2.100
0.009
0.0589

Partial Solution: The data can be read with the following statements
D = load(xydy.dat);

x = D(:,1);

y = D(:,2);

dy = D(:,3);

The desired plot is shown below


0.7

0.6

0.5

0.4

0.3

0.2

Plot of solution to
Exercise 230.

0.1

-0.1
-0.5

0.5

1.5

2.5

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Selected Solutions for Exercises in

Numerical Methods with Matlab:


Implementations and Applications
Gerald W. Recktenwald
Chapter 3
Matlab Programming

The following pages contain solutions to selected end-of-chapter Exercises


from the book Numerical Methods with Matlab: Implementations and
c 2003, Prentice-Hall, Upper
Applications, by Gerald W. Recktenwald, 
c 2003 Gerald W. Recktenwald. The
Saddle River, NJ. The solutions are 
PDF version of the solutions may be downloaded or stored or printed only
for noncommercial, educational use. Repackaging and sale of these solutions
in any form, without the written consent of the author, is prohibited.
The latest version of this PDF le, along with other supplemental material
for the book, can be found at www.prenhall.com/recktenwald.

Matlab Programming

3.3 Transform the takeout script in Listing 3.2 to a function. Add a single input argument called
kind that allows you to select a type of food from your list of favorite take-out restaurants. Inside
the body of the function, set up a multiple-choice if ... elseif ... end block to match the
kind string with the predened restaurant types. Make sure that there is a default choiceeither a
restaurant type or an error messageif kind does not match any of the available restaurant types.
(Hint: use the strcmp function to compare to strings for equality.)
Solution: The takeout2 function, listed below, is a solution to the assignment. Note that disp
functions have been used to display the restaurant name and number to the screen. This is better
at conveying the intent of the program, which is to print the name and telephone number. A reader
of the original takeout function might conclude that the purpose of the function is to assign values
that are not used in any subsequent statements not an obvious purpose.
You should test the takeout2 program. What happens if you misspell one of the kinds, for example,
by entering takeout2(burgur)? An alternative implementation of the function would provide a
default restaurant instead of an error message. While you are at it, you might as well replace the
ctitious restaurants with real restaurants in your neighborhood.
function takeout2(kind)
% takeout2 Display restaurant telephone numbers.
Exercise 3-3
%
% Synopsis: takeout2(kind)
%
% Input:
kind = (string) type of food. Example: kind = pizza
%
% Output: Print out of telephone numbers for restaurants matching kind
if strcmp(kind,chinese)
disp(Mandarin Cove 221-8343);
elseif strcmp(kind,pizza)
disp(Pizza Express
335-7616);
elseif strcmp(kind,deli)
disp(Bernstein Deli
239-4772);
elseif strcmp(kind,burger)
disp(Big Burger
629-4085);
elseif strcmp(kind,mexican)
disp(Burrito Barn
881-8844);
elseif strcmp(kind,veggie)
disp(Tofu Palace
310-7900);
else
error(sprintf("%s" does not match one of the restaurant types,kind));
end

c 2003, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 3: Matlab Programming

3.5 Write a newtsqrt function to compute the square root of a number, using Newtons algorithm.
Your function should encapsulate the code on page 115.
Solution: A version of newtsqrt is listed below. Does it work? What are the results of newtsqrt(4),
newtsqrt(400), newtsqrt(4e-16)?
function r = newtsqrt(x,delta,maxit)
% newtsqrt Newtons method for computing the square root of a number
%
Exercise 3-5
%
% Synopsis: r = newtsqrt(x)
%
r = newtsqrt(x,delta)
%
r = newtsqrt(x,delta,maxit)
%
% Input:
x
= number for which the square root is desired
%
delta = (optional) convergence tolerance. Default: delta = 5e-6
%
maxit = (optional) maximum number of iterations. Default: maxit = 25
%
% Output:
r = square root of x to within relative tolerance of delta
%
The kth iterate for the square root of x is
%
%
r(k) = 0.5*( r(k-1) + x/r(k-1))
%
%
Iterations are terminated after maxit iterations or
%
when abs(r(k-1)-r(k))/r(k-1) < delta
if x<0,

error(Negative input to newtsqrt not allowed);

if nargin<2,
if nargin<3,

delta = 5.0e-6;
maxit = 25;

end
end

end

Defaults for optional input arguments

r = x;
% Initialize
rold = 2*r;
% Make sure convergence test fails on first try
it = 0;
while abs(rold-r)/rold > delta & it<maxit
rold = r;
% Save old value for convergence test
r = 0.5*(rold + x/rold);
% Update the guess at the root
it = it + 1;
% Increment the iteration counter
end

c 2003, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Matlab Programming

3.7 Elvis Presley was born January 8, 1935, and died on August 16, 1977. Write an elvisAge
function that returns Elviss age in years, assuming that he were alive today. (The fragment of code
on page 103 may be of some help.)
Solution:

The elvisAge1 function is listed on the following page. Does it work?

function y = elvisAge1
% elvisAge Compute age of Elvis Presley (assuming hes still alive)
%
Solutions to Exercise 3-7
%
% Synopsis:
y = elvisAge1
%
% Input: none
%
% Output: y = years since Elvis was born on 8 January 1935
theDate = datevec(now);
% measure age from todays date
birthdate = datevec(datenum(1935,1,8));
deltaTime = theDate - birthdate;
% vector of time differences
y = deltaTime(1);
if ( birthdate(2) >= theDate(2) ) & ( birthdate(3) > theDate(3) )
y = y - 1;
% birthdate hasnt happened yet this month
end

c 2003, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 3: Matlab Programming

3.10 Write a function called mydiag that mimics the behavior of the built-in diag function. At a
minimum, the mydiag function should return a diagonal matrix if the input is a vector, and return
the diagonal entries of the matrix if the input is a matrix. (Hint: The size function will be helpful.)
Partial Solution: An incomplete version of the myDiag function is listed below. Your job is to
nish myDiag and verify that it works. Use the demoMyDiag function, listed on the next page, and
any other tests you wish to devise, to validate your implementation of myDiag.
function D = myDiag(A)
% myDiag Create a diagonal matrix, or extract the diagonal of a matrix
%
% Synopsis: D = myDiag(A) to extract a diagonal elements from a matrix A
%
% Input: A = a vector or a matrix
%
% Output: If A is a vector, D is a diagonal matrix with the elements
%
of v on the diagonal. If A is a matrix, D is a vector
%
containing the diagonal elements of A.
[m,n] = size(A);
if min(m,n)==1
%
r = max(m,n);
%
D = zeros(r,r);

input is a vector
m=1 or n=1, pick largest to dimension D

... your code here


else

input is a matrix

... your code here


end

function demoMyDiag
% demoMyDiag Test the myDiag function.

Exercise 3-10

% --- Test creation of diagonal matrices


fprintf(\nVerify that myDiag correctly creates diagonal matrices\n);
fprintf(
m
error\n);
for m = [1 4 7 13 20]
v = rand(m,1);
D1 = diag(v);
D2 = myDiag(v);
fprintf( %3d
%12.3e\n,m,norm(D1-D2,Inf));
end
% --- Test extraction of diagonal vector
fprintf(\nVerify that myDiag correctly extracts the diagonal of a matrix\n);
fprintf(
m
n
error\n);
for m = [1 4 20]
for n = [1 5 17]
A = rand(m,n);
d1 = diag(A);
d2 = myDiag(A);
fprintf( %3d
%3d
%12.3e\n,m,n,norm(d1-d2));
end
end

Running demoMyDiag for a correct implementation of myDiag gives


c 2003, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Matlab Programming

6
>> demoMyDiag
Verify that myDiag correctly creates diagonal matrices
m
error
1
0.000e+00
4
0.000e+00
7
0.000e+00
13
0.000e+00
20
0.000e+00
Verify that myDiag correctly extracts the diagonal of a matrix
m
n
error
1
1
0.000e+00
1
5
-0.000e+00
1
17
-0.000e+00
4
1
-0.000e+00
4
5
0.000e+00
4
17
0.000e+00
20
1
-0.000e+00
20
5
0.000e+00
20
17
0.000e+00

c 2003, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 3: Matlab Programming

3.16 Write the Matlab statements that use a loop and the fprintf function to produce the
following table (the format of the numerical values should agree exactly with those printed in the
table).
theta
0
60
120
180
240
300
360

sin(theta)
0.0000
0.8660
0.8660
-0.0000
-0.8660
-0.8660
0.0000

Partial Solution:
fprintf(%6d

cos(theta)
1.0000
0.5000
-0.5000
-1.0000
-0.5000
0.5000
1.0000

The body of the loop can be one line:


%9.4f

%9.4f\n,thetad(k),sin(thetar(k)),cos(thetar(k)))

Many other loop blocks can be made to work.

c 2003, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Matlab Programming

3.22 Write a function to plot the displacement of a cantilevered beam under a uniform load. In
addition to creating the plot, the function should return the maximum deection and angle between
the horizontal and the surface of the beam at its tip. The formulas for the displacement y and tip
angle are

1 wL3
wx2  2
6L 4Lx + x2
,
and
=
y=
24EI
6 EI
where w is the load per unit length, E is Youngs modulus for the beam, I is the moment of inertia
of the beam, and L is the length of the beam. Test your function with E = 30 Mpsi, I = 0.163 in4 ,
L = 10 in, w = 100 lbf /in.
Partial Solution: The cantunif function, listed below, evaluates the formulas for the displacement y and tip angle for any set of E, I, L, and w values. The cantunif function also plots y(x).
To complete the Exercise, the cantunif function is called with the appropriate inputs. What is the
value of ymax and for the given values of E, I, L, and w?
function [ymax,theta] = cantunif(E,I,L,w)
% cantunif Plot the deflection of a uniformly loaded cantilevered beam.
%
Return the maximum deflection and the slope at the tip. Exercise 3-22
%
% Synopsis: [ymax,theta] = cantunif(E,I,L,w)
%
% Input: E = Youngs modulus
%
I = moment of inertia of the beam
%
L = length of the beam
%
w = uniform load on the beam (weight per unit length)
%
% NOTE: inputs must have internally consistent units
%
% Output: ymax = maximum deflection at the tip
%
theta = angle in radians between horizontal and the
%
beam surface at the tip
x = linspace(0,L);
y = -w*x.^2 .* (x.^2 + 6*L^2 - 4*L*x)/(24*E*I);
ymax = max(abs(y));
if ymax~=abs(y(end))
% displacement formula should gives max at x=L
warning(Max displacement not at tip?);
fprintf(y(end) = %g, ymax = %g\n,y(end),ymax)
end
theta = w*L^3/(6*E*I);
plot(x,y);
xlabel(Position along the beam);
ylabel(Displacement under uniform load);
title(sprintf(E = %g, I = %5.3f, L = %g, w = %g,E,I,L,w));

c 2003, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 3: Matlab Programming

3.28 The corvRain.dat le in the data directory of the NMM toolbox contains monthly precipitation data for Corvallis, Oregon, from 1890 to 1994. The data are organized into columns, where
the rst column lists the year and the next 12 columns give the precipitation, in hundredths of an
inch for each month. Write a Matlab function to compute and plot the yearly total precipitation
in inches (not hundredths of an inch) from 1890 to 1994. The function should also print the average,
the highest, and the lowest annual precipitation for that period. The loadColData function in the
utils directory of the NMM toolbox will be helpful in reading the data without having to delete
the column headings. Can you compute the yearly total precipitation without using any loops?
Partial Solution: The beginning of the precip function is listed below. This function takes a
data le (corvRain.dat in this case) as input, and computes the precipitation totals. Your job is
to nish the precip function.
function precip(fname)
% precip Plot precipitation data from OSU Weather Service.
%
Uses loadColData() function to import data and labels.
%
% Synopsis: precip(fname)
%
% Input:
fname = name of file containing the plot data
%
% Output:
Plot of annual rainfall. Compute and print the average,
%
low and high values of yearly rainfall
% Data file has 13 columns of data, 1 header of text, 1 row of column labels
[year,P,labels] = loadColData(fname,13,1);
% --- Sum over rows of P to get annual precipitation.
% sum(P) adds entries in each *column* of P.
We need sum over
% rows of the P matrix, so use sum(P). After the sum is performed
% convert from hundredths of an inch to inches, and transpose
% again so that the yearly total is stored in a column vector.
pt = (sum(P)/100);
... your code goes here

Running the completed precip function gives the following output. Note that the formatting of the
output is not important. The numerical values will be helpful, however, as a check on your complete
program.
>> precip(corvrain.dat)
Summary of precipitation data from file corvrain.dat
Average annual precipitation = 40.3 inches
Highest annual precipitation = 58.7 inches
Lowest annual precipitation = 23.0 inches

3.31 Write a function called maxi to return the index of the most positive element in a vector. In
other words imax = maxi(v) returns imax such that v(imax) v(i) for all i.
Solution: The complete maxi function is listed below. To complete the Exercise, use the two
parameter form of the max function to test maxi for a variety of vector inputs.
c 2003, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

10

Matlab Programming
function imax = maxi(v)
% maxi Given vector v, find imax such that v(imax) >= v(i) for all i
%
Use a for loop. Exercise 3-31
imax = 1;
for i = 2:length(v)
if v(i)>v(imax), imax=i; end
end

c 2003, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 3: Matlab Programming

11

3.43 Write an m-le function to compute the heat transfer coecient for a cylinder in cross ow.
The heat transfer coecient h is dened in terms of the dimensionless Nusselt number Nu = hd/k,
where d is the diameter of the cylinder and k is the thermal conductivity of the uid. The Nusselt
number is correlated with the Reynolds number Re and Prandtl number Pr by
Nu = CRem Pr1/3 ,

where

Re =

V d

and Pr =

cp
,
k

in which , , and cp are, respectively, the density, dynamic viscosity, and specic heat of the uid
and V is the velocity of the uid approaching the cylinder. The parameters C and m depend on Re
according to the following table:
Re range
0.4 4
4 40
40 4000
4000 40,000
40,000 400,000

c
0.989
0.911
0.683
0.193
0.027

m
0.330
0.385
0.466
0.618
0.805

Use the following for the rst line of your m-le


function h = cylhtc(d,v)

where d is the cylinder diameter and v is the uid velocity. Use the properties of air at one atmosphere
and 20 C.
3

= 1.82 105 N s/m2 ,

= 1.204 kg/m ,

cp = 1007 J/(kg K),

k = 26.3 103 W/(m C)

Typographical Error: In the rst printing of the text, the value of k is given as 26.3 W/(m C),
which is o by a factor of 1000. The correct value of the thermal conductivity is k = 26.3
103 W/(m C).
Partial Solution: The values of c and m are set with an extended if...else construct. The
beginning of the construct looks like.
if Re < 0.4
error(sprintf(Re = %e is too low for correlation; min Re is 0.4,Re));
elseif Re < 4
c = 0.989;
m = 0.330;
...

A demoCylhtc function (not listed here) was written to test cylhtc. Running demoCylhtc gives the
following output.
>> demoCylhtc
diameter
m
0.001
0.010
0.200
0.200
0.200

velocity
m/s
0.008
0.008
0.015
1.500
15.000

Re
0.53
5.29
198.46
19846.15
198461.54

h
W/(m^2 C)
18.693
4.035
0.937
10.190
57.894

c 2003, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Selected Solutions for Exercises in

Numerical Methods with Matlab:


Implementations and Applications
Gerald W. Recktenwald
Chapter 4
Organizing and Debugging
Matlab Programs

The following pages contain solutions to selected end-of-chapter Exercises


from the book Numerical Methods with Matlab: Implementations and
c 2000, Prentice-Hall, Upper
Applications, by Gerald W. Recktenwald, 
c 2000 Gerald W. Recktenwald. The
Saddle River, NJ. The solutions are 
PDF version of the solutions may be downloaded or stored or printed only
for noncommercial, educational use. Repackaging and sale of these solutions
in any form, without the written consent of the author, is prohibited.
The latest version of this PDF le, along with other supplemental material
for the book, can be found at www.prenhall.com/recktenwald.

Organizing and Debugging

4.2 Use stepwise renement to describe all of the steps necessary to compute the average and
standard deviation of the elements in a vector x. Implement these tasks in an m-le, and test your
solution. Do not use the built-in mean and std functions. Rather, develop your solution from the
equations for the average and standard deviation of a nite sample.
Partial Solution: Given an n-element vector x, the formulas for computing the mean x
and
variance 2 are
n
n
1
1 
x
=
xi
2 =
(xi x
)2
n i=1
n 1 i=1
The standard deviation is .
The tasks necessary for computing x
and are
(a) Read the data into x (or accept x as input to a function)
(b) Determine n, the length of the data set
(c) Compute x
and using the formulas given above
(d) Display the results (or return them to the calling function)
The implementation can be tested with (at least) the following cases
Data set with n = 1. Is there an error trap for ?
Data set with n = 2. Then x
= (x1 + x2 )/2, = (x2 x1 )2 /2.
= K and = 0.
Data set of arbitray length with all xi = K, where K is a constant. Then x
Implementation of the code for computing x
and is complicated in the case where n is large. For
large n
The available memory (RAM) may not be large enough to hold all the data at once.
Computation of x
and may cause overow errors.
Computation of both x
and will suer loss of signicance if the sums are computed as written.

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Selected Solutions for Exercises in

Numerical Methods with Matlab:


Implementations and Applications
Gerald W. Recktenwald
Chapter 5
Unavoidable Errors in Computing

The following pages contain solutions to selected end-of-chapter Exercises


from the book Numerical Methods with Matlab: Implementations and
c 2000, Prentice-Hall, Upper
Applications, by Gerald W. Recktenwald, 
c 2000 Gerald W. Recktenwald. The
Saddle River, NJ. The solutions are 
PDF version of the solutions may be downloaded or stored or printed only
for noncommercial, educational use. Repackaging and sale of these solutions
in any form, without the written consent of the author, is prohibited.
The latest version of this PDF le, along with other supplemental material
for the book, can be found at www.prenhall.com/recktenwald.

Unavoidable Errors in Computing

53 Convert the following numbers to normalized oating-point values with eight-bit mantissas:
0.4, 0.5, 1.5.
Partial Solution: 0.4 = 0.4 100 is already is already in normalized format. Converting
0.4 to a binary number using Algorithm 5.1 gives (0 1100 1100 1100 . . .)2 . To eight bits we get
0.4 = (01100110)2 . Converting (01100110)2 back to base 10 with Equation (5.2) gives
0 21 + 1 22 + 1 23 + 0 24 + 0 25 + 1 26 + 1 27 + 0 28
1
1
1 1
+
= 0.398437500
= + +
4 8 64 128

59 Modify the epprox function in Listing 5.2 on page 207 so that vectors of n and abs(f-e) are
saved inside the loop. (Hint: Create the nn and err vectors, but do not modify the loop index
n.) Remove (i.e., comment out) the fprintf statements, and increase the resolution of the
loop by changing the for statement to for n=logspace(1,16,400). Plot the variation of the
absolute error with n. Do not connect the points with line segments. Rather, use a symbol,
such as + for each point. Explain the behavior of the error for n > 107 .
Partial Solution: The epproxPlot function, listed below, contains the necessary modications. Running epproxPlot produces the plot on the following page. Explanation of the plot
is left as an exercise to the reader.

function epproxPlot
% epproxPlot Plot error in approximating e = exp(1) with the f(n)
%
f(n) = lim_{n->infinity} (1 + 1/n)^n
%
% Synopsis: y = epproxPlot
%
% Input:
none
%
% Output:
Plot comparing exp(1) and f(n) = (1 + 1/n)^n as n -> infinity
%
%

Ref:

N.J. Higham, Accuracy and Stability of Numerical Algorithms,


1996, SIAM, section 1.11

e = exp(1);
% fprintf(\n
n
f(n)
error\n);
k=0;
for n=logspace(1,16,400)
f = (1+1/n)^n;
% fprintf(%9.1e %14.10f %14.10f\n,n,f,abs(f-e));
k = k + 1;
nn(k) = n;
err(k) = abs(f-e);
end
loglog(nn,err,+);
xlabel(n);
ylabel(Absolute error in f(n));
[minerr,imin] = min(err);
fprintf(\nMinimum error = %11.3e occurs for n = %24.16e in this sample\n,...
minerr,nn(imin));

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 5: Unavoidable Errors in Computing

10

10

-2

Absolute error in f(n)

10

-4

10

-6

10

Plot of solution to
Exercise 59.

-8

10

-10

10

10

10

10

10

10
n

10

10

12

10

14

10

16

10

519 Implement the combined tolerance |xk xk1 | < max [a , r |xk1 |] in the newtsqrt function
in Listing 5.3. Note that a and r should be separate inputs to your newtsqrt function. As a
diagnostic, print the number of iterations necessary to achieve convergence for each argument
of newtsqrt. Based on the results of Example 5.6, what are good default values for a and r ?
If a = r , is the convergence behavior signicantly dierent than the results of Example 5.6?
Is the use of an absolute tolerance helpful for this algorithm?
Partial Solution: The Matlab part of the solution is implemented in the newtsqrt and
testConvSqrt functions listed below. The newtsqrt function is a modied version of the
newtsqrtBlank.m le in the errors directory of the NMM Toolbox. The modied le is saved
as newtsqrt.m. The testConvSqrt function is a modied version of testsqrt function in
Listing 5.4.
The inputs to newtsqrt
are x, the argument of the square root function (newtsqrt returns
an approximation to x), deltaA, the absolute tolerance, deltaR, the relative tolerance, and
maxit, the maximum number of iterations. Note that the newtsqrt function has two input
tolerances, whereas the newtsqrt function in Listing 5.3 has only one tolerance (delta). The
default tolerances in testConvSqrt are
deltaA = 5m = 1.11 1015
deltaR = 5 106
The absolute tolerance is designed prevent unnecessary iterations: values of r rold less than
m are meaningless due to roundo. The relative tolerance corresponds to a change in the
estimate of the root of less than 0.05 percent (0.0005) on subsequent iterations.
c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Unavoidable Errors in Computing


function testConvSqrt(deltaA,deltaR)
% testConvSqrt Test alternative convergence criteria for the newtsqrt function
%
% Synopsis: testConvSqrt
%
testConvSqrt(deltaA)
%
testConvSqrt(deltaA,deltaR)
%
% input: deltaA = (optional) absolute convergence criterion
%
Default: deltaA = 5e-9
%
deltaR = (optional) relative convergence criterion
%
Default: deltaR = 5e-6
if nargin<1,
if nargin<2,
xtest = [4

deltaA = 5*eps; end


deltaR = 5e-6; end

0.04

4e-4

4e-6

4e-8

4e-10

4e-12];

% arguments to test

fprintf(\n Combined Convergence Criterion\n);


fprintf(\t\t deltaA = %12.4e\t\t deltaR = %12.4e\n\n,deltaA,deltaR)
fprintf(
x
sqrt(x)
newtsqrt(x)
error
relerr

it\n);

for x=xtest
% repeat for each column in xtest
r = sqrt(x);
[rn,it] = newtsqrt(x,deltaA,deltaR);
err = abs(rn - r);
relerr = err/r;
fprintf(%10.3e %10.3e %10.3e %10.3e %10.3e %4d\n,x,r,rn,err,relerr,it)
end

function [r,iter] = newtsqrt(x,deltaA,deltaR,maxit)


% newtsqrt
Use Newtons method to compute the square root of a number
%
% Synopsis: r = newtsqrt(x,delta,maxit)
%
[r,it] = newtsqrt(x,delta,maxit)
%
% Input: x
= number for which the square root is desired
%
delta = (optional) convergence tolerance. Default: delta = 5e-9
%
maxit = (optional) maximum number of iterations. Default: maxit = 25
%
% Output:
r = square root of x to within combined tolerance
%
abs(r-rold) < max( deltaA, deltaR*abs(rold) )
%
where r is the current guess at the root and rold
%
is the guess from the previous iteration
%
it = (optional) number of iterations to reach convergence
if
if
if
if
if

x<0, error(Negative input to newtsqrt not allowed);


x==0,
r=x; return;
end
nargin<2, deltaA = 5*eps; end
nargin<3, deltaR = 5e-6; end
nargin<4, maxit=25;
end

end

r = x/2; rold = x;
% Initialize, make sure convergence test fails on first try
it = 0;
while abs(r-rold) > max( [deltaA, deltaR*abs(rold)] ) & it<maxit % Convergence test
rold = r;
% Save old value for next convergence test
r = 0.5*(rold + x/rold);
% Update the guess
it = it + 1;
end
if nargout>1, iter=it; end

The reader is left with the task of running testConvSqrt and discussing the results. What
happens if the call to testConvSqrt is testConvSqrt(5e-9)? Which tolerance, the absolute
or the relative (or both, or neither) is more eective at detecting convergence?

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 5: Unavoidable Errors in Computing

523 Use the sinser function in Listing 5.5 to evaluate sin(x), for x = /6, 5/6, 11/6, and
17/6. Use the periodicity of the sine function to modify the sinser function to avoid the
undesirable behavior demonstrated by this sequence of arguments. (Hint: The modication
does not involve any change in the statements inside the for...end loop.)
Partial Solution: The output of running sinser for x = 17/16 is
>> sinser(17*pi/6)
Series approximation to sin(8.901179)
k
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29

term
8.901e+00
-1.175e+02
4.656e+02
-8.784e+02
9.666e+02
-6.963e+02
3.536e+02
-1.334e+02
3.886e+01
-9.003e+00
1.698e+00
-2.659e-01
3.512e-02
-3.964e-03
3.868e-04

ssum
8.90117919
-108.64036196
357.00627682
-521.41383256
445.22638523
-251.02690828
102.59385039
-30.82387869
8.03942600
-0.96401885
0.73443795
0.46848851
0.50360758
0.49964387
0.50003063

Truncation error after 15 terms is 3.06329e-05


ans =
0.5000

Due to the large terms in the numerator, the value of the series rst grows before converging
toward the exact value of 0.5. Since the large terms alternate in sign, there is a loss of precision
in the least signicant digits when the large terms with opposite sign are added together to
produce a small result. Thus, even if more terms are included in the series, it is not possible to
obtain arbitrarily small errors. Evaluating the series for the sequence x = /6, 5/6, 11/6,
17/6,. . . requires an increasing number of terms, even though | sin(x)| = 1/2 for each x in the
sequence.
The results of running sinser for x = /6, 5/6, 11/6, and 17/6 are summarized in the
table below.
x

Terms

Absolute Error

/6

3.56 1014

5/6

10

1.16 1011

11/6

15

4.40 1011

17/6

15

3.06 1005

For smaller values of x, the series converges with fewer terms. The error in the approximation
to sin(x) grows as |x| increases.
c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Unavoidable Errors in Computing


To reduce the eect of roundo for large x we exploit the periodicity of sin(x): the value of
sin(x) is the same for x 2n for n = 1, 2, . . .. Thus, whenever |x| > 2 we can remove an
integer factor of 2 before evaluating the series. Removing an integer factor of 2 is easily
achieved with the built-in rem function. rem(a,b) returns the remainder (fractional part) of
a/b. To apply this to the sinser code, insert
x = rem(x,2*pi);

before the evaluation of the series. This x is implemented in sinserMod (not listed here).
Running sinserMod for x = 11/6 gives
>> s = sinserMod(17*pi/6)
Series approximation to sin(2.617994)
k
1
3
5
7
9
11
13
15
17
19

term
2.618e+00
-2.991e+00
1.025e+00
-1.672e-01
1.592e-02
-9.920e-04
4.358e-05
-1.422e-06
3.584e-08
-7.183e-10

ssum
2.61799388
-0.37258065
0.65227309
0.48502935
0.50094978
0.49995780
0.50000139
0.49999996
0.50000000
0.50000000

Truncation error after 10 terms is 1.15644e-11


s =
0.5000

The sinserMod function obtains a more accurate result than sinser, and it does so by evaluating fewer terms.
A even better solution involves recognizing that sin(x) for all x can be constructed from a table
of sin(x) values for 0 < x < /2. The diagram below indicates how values of sin(x) versus x
can be used to generate sin(x) values for any x.
1.5

0.5

Exercise 523. All values of


sin(x) can be generated from
sin(x) versus x in 0 x /2.

-0.5

-1

-1.5

-8

-6

-4

-2

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 5: Unavoidable Errors in Computing

The following table gives additional clues on how to implement a more ecient and more
accurate sinser
Range of x

<x<
2
3
<x<
2
3
< x < 2
2

Simplication
sin(x) = sin( x)
sin(x) = sin(x ) = sin(x )
sin(x) = sin(2 x) = sin(x 2)

The range of x < 0 is handled with the identity sin(x) = sin(x).


The following Matlab code provides additional hints on the implementation.
x = rem(x,2*pi);
if x==0
ssum = 0;
return;
elseif x==pi/2
ssum = sign(xin);
return;
elseif x>pi/2 & x<pi
x = pi - x;
...

The goal of the more sophisticated code is to use the absolute minimum number of terms in the
series approximation. Reducing the number of terms makes the computation more ecient,
but more importantly, it reduces the roundo.
The improved code is contained in the sinserMod2 function, which is not listed here. The
demoSinserMod2 function compares the results of sinserMod and sinserMod2 for x = /6,
5/6, 11/6, and 17/6. Running demoSinserMod2 gives
>> demoSinserMod2

x*6/pi
-17.00
-11.00
-5.00
-1.00
1.00
5.00
11.00
17.00

-- sinserMod -n
err
10
1.156e-11
15
-4.402e-11
10
1.156e-11
6
3.564e-14
6
-3.564e-14
10
-1.156e-11
15
4.402e-11
10
-1.156e-11

-- sinserMod2 -n2
err2
6
3.558e-14
6
-3.558e-14
6
3.564e-14
6
3.564e-14
6
-3.564e-14
6
-3.564e-14
6
3.558e-14
6
-3.558e-14

For the same tolerance (5 109 ) sinserMod2 obtains a solution that is as or more accurate
than sinserMod, and it does so in fewer iterations. For x = 5/6 the two functions are
identical. Complete implementation and testing of sinserMod and sinserMod2 is left to the
reader.

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Unavoidable Errors in Computing

527 Derive the Taylor series expansions P1 (x), P2 (x), and P3 (x) in Example 5.9 on page 222.
Partial Solution: The Taylor polynomial is given by Equation (5.15)



df 
(x x0 )2 d2 f 
(x x0 )n dn f 
Pn (x) = f (x0 ) + (x x0 )
+
+ +
dx x=x0
2
dx2 x=x0
n!
dxn x=x0
Given f (x) = 1/(1 x) we compute
+1
df
=
dx
(1 x)2

d2
+2
=
2
dx
(1 x)3

d3
+6
=
3
dx
(1 x)4

Thus
P1 (x) = f (x0 ) + (x x0 )

dn
n!
=
n
dx
(1 x)n+1

1
(1 x0 )2

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Selected Solutions for Exercises in

Numerical Methods with Matlab:


Implementations and Applications
Gerald W. Recktenwald
Chapter 6
Finding the Roots of f (x) = 0

The following pages contain solutions to selected end-of-chapter Exercises


from the book Numerical Methods with Matlab: Implementations and
c 2000, Prentice-Hall, Upper
Applications, by Gerald W. Recktenwald, 
c 2000 Gerald W. Recktenwald. The
Saddle River, NJ. The solutions are 
PDF version of the solutions may be downloaded or stored or printed only
for noncommercial, educational use. Repackaging and sale of these solutions
in any form, without the written consent of the author, is prohibited.
The latest version of this PDF le, along with other supplemental material
for the book, can be found at www.prenhall.com/recktenwald.

Finding the Roots of f (x) = 0

62 The function f (x) = sin(x2 ) + x2 2x 0.09 has four roots in the interval 1 x 3. Given
the m-le fx.m, which contains
function f = fx(x)
f = sin(x.^2) + x.^2 - 2*x - 0.09;

the statement
>> brackPlot(fx,-1,3)

produces only two brackets. Is this result due to a bug in brackPlot or fx? What needs to
be changed so that all four roots are found? Demonstrate that your solution works.
Partial Solution: The statement
>> Xb = brackPlot(fx,-1,3)
Xb =
-0.1579
0.0526
2.1579
2.3684

returns two brackets. A close inspection of the plot of f (x) reveals that f (x) crosses the x-axis
twice near x = 1.3. These two roots are missed by brackPlot because there default search
interval is too coarse. There is no bug in brackPlot. Implementing a solution using a ner
search interval is left as an exercise.
611 Use the bisect function to evaluate the root of the Colebrook equation (see Exercise 8)
for /D = 0.02 and Re = 105 . Do not modify bisect.m. This requires that you write an
appropriate function m-le to evaluate the Colebrook equation.
Partial Solution: Using bisect requires writing an auxiliary function to evaluate the Colebrook equation in the form F (f ) = 0, where f is the friction factor. The following form of
F (f ) is used in the colebrkz function listed below.


/D
2.51
1

+
F (f ) = + 2 log10
3.7
f
ReD f
Many other forms of F (f ) will work.
function ff = colebrkz(f)
% COLEBRKZ Evaluates the Colebrook equation in the form F(f) = 0
%
for use with root-finding routines.
%
% Input:
f = the current guess at the friction factor
%
% Global Variables:
%
EPSDIA = ratio of relative roughness to pipe diameter
%
REYNOLDS = Reynolds number based on pipe diameter
%
% Output: ff = the "value" of the Colebrook function written y = F(f)
% Global variables allow EPSDIA and REYNOLDS to be passed into
% colebrkz while bypassing the bisect.m or fzero function
global EPSDIA REYNOLDS
ff = 1.0/sqrt(f) + 2.0*log10( EPSDIA/3.7 + 2.51/( REYNOLDS*sqrt(f) ) );

Because the bisect function (unlike fzero) does not allow additional parameters to be passed
through to the F (f ) function, the values of /D and Re are passed to colebrkz via global
variables. Running bisect with colebrkz is left to the reader. For Re = 1 105 and
/D = 0.02 the solution is f = 0.0490.
c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 6: Finding the Roots of f (x) = 0

613 Derive the g3 (x) functions in Example 6.4 and Example 6.5. (Hint: What is the xed-point
formula for Newtons method?)
Partial Solution: The xed point iteration formulas designated as g3 (x) in Example 6.4
and Example 6.5 are obtained by applying Newtons method. The general form of Newtons
method for a scalar variable is
f (xk )
xk+1 = xk 
f (xk )
Example 6.4: The f (x) function and its derivative are
1
f  (x) = 1 x2/3
3

f (x) = x x1/3 2

Substituting these expressions into the formula for Newtons method and simplifying gives
1/3

xk+1 = xk

xk xk
1

2/3
(1/3)xk

2/3

xk (1 (1/3)xk

xk (1/3)xk

(2/3)xk

1/3

xk + xk

1
2xk
3

1/3

2)

+2

2/3
(1/3)xk

+2

2/3
(1/3)xk

1/3

2/3
(1/3)xk

1
1/3

1/3

) (xk xk

+6

2/3
xk

Repeating this analysis for Example 6.5 is left as an exercise.

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Finding the Roots of f (x) = 0

617 K. Wark and D. E. Richards (Thermodynamics, 6th ed., 1999, McGraw-Hill, Boston, Example
14-2, pp. 768769) compute the equilibrium composition of a mixture of carbon monoxide and
oxygen gas at one atmosphere. Determining the nal composition requires solving
3.06 =

(1 x)(3 + x)1/2
x(1 + x)1/2

for x. Obtain a xed-point iteration formula for nding the roots of this equation. Implement
your formula in a Matlab function and use your function to nd x. If your formula does not
converge, develop one that does.
Partial Solution: One xed point iteration formula is obtained by isolating the factor of
(3 + x) in the numerator.
3.06x(1 + x)1/2
= (3 + x)1/2
1x

3.06x(1 + x)1/2
x=
1x

g1 (x) =

2
3

3.06x(1 + x)1/2
1x

2
3

Another xed point iteration formula is obtained by solving for the isolated x in the denominator to get
x=

(1 x)(3 + x)1/2
3.06(1 + x)1/2

g2 (x) =

(1 x)(3 + x)1/2
3.06(1 + x)1/2

Performing 10 xed point iterations with g1 (x) gives


it
1
2
3
4
5
6
7
8
9
10

xnew
-7.6420163e-01
-2.5857113e+00
-1.0721050e+01
-7.9154865e+01
-7.1666488e+02
-6.6855377e+03
-6.2575617e+04
-5.8590795e+05
-5.4861826e+06
-5.1370394e+07

Thus, g1 (x) does not converge. The g2 (x) function does converge to the true root of x =
0.340327 . . .. Matlab implementations of the xed point iterations are left as an Exercise.

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 6: Finding the Roots of f (x) = 0

624 Create a modied newton function (say, newtonb) that takes a bracket interval as input instead
of a single initial guess. From the bracket limits take one bisection step to determine x0 , the
initial guess for Newton iterations. Use the bracket limits to develop relative tolerances on x
and f (x) as in the bisect function in Listing 6.4.
Solution: The newtonb function is listed below. The demoNewtonb function, also listed below,
repeats the calculations in Example 6.8 with the original newton function and with the new
newtonb function.
Running demoNewtonb gives
>> demoNewtonb
Original newton function:
Newton iterations for fx3n.m
k
f(x)
dfdx
1
-4.422e-01
8.398e-01
2
4.507e-03
8.561e-01
3
3.771e-07
8.560e-01
4
2.665e-15
8.560e-01
5
0.000e+00
8.560e-01

x(k+1)
3.52664429313903
3.52138014739733
3.52137970680457
3.52137970680457
3.52137970680457

newtonb function:
Newton iterations for fx3n.m
k
f(x)
dfdx
1
-4.422e-01
8.398e-01
2
4.507e-03
8.561e-01
3
3.771e-07
8.560e-01
4
2.665e-15
8.560e-01
5
0.000e+00
8.560e-01

x(k+1)
3.52664429313903
3.52138014739733
3.52137970680457
3.52137970680457
3.52137970680457

The two implementations of Newtons method give identical results because the input to
newtonb is the bracket [2, 4]. This causes the initial bisection step to produce the same initial
guess for the Newton iterations that is used in the call to newton.
function demoNewtonb
% demoNewtonb Use newton and newtonb to find the root of f(x) = x - x^(1/3) - 2
%
% Synopsis: demoNewton
%
% Input:
none
%
% Output
print out of convergence history, and comparison of methods
fprintf(\nOriginal newton function:\n);
r = newton(fx3n,3,5e-16,5e-16,1);
fprintf(\nnewtonb function:\n);
rb = newtonb(fx3n,[2 4],5e-16,5e-16,1);

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Finding the Roots of f (x) = 0

function r = newtonb(fun,x0,xtol,ftol,verbose)
% newtonb
Newtons method to find a root of the scalar equation f(x) = 0
%
Initial guess is a bracket interval
%
% Synopsis: r = newtonb(fun,x0)
%
r = newtonb(fun,x0,xtol)
%
r = newtonb(fun,x0,xtol,ftol)
%
r = newtonb(fun,x0,xtol,ftol,verbose)
%
% Input: fun
= (string) name of mfile that returns f(x) and f(x).
%
x0
= 2-element vector providing an initial bracket for the root
%
xtol
= (optional) absolute tolerance on x.
Default: xtol=5*eps
%
ftol
= (optional) absolute tolerance on f(x). Default: ftol=5*eps
%
verbose = (optional) flag. Default: verbose=0, no printing.
%
% Output: r = the root of the function
if nargin < 3, xtol = 5*eps; end
if nargin < 4, ftol = 5*eps; end
if nargin < 5, verbose = 0;
end
xeps = max(xtol,5*eps); feps = max(ftol,5*eps);

Smallest tols are 5*eps

if verbose
fprintf(\nNewton iterations for %s.m\n,fun);
fprintf( k
f(x)
dfdx
x(k+1)\n);
end
xref = abs(x0(2)-x0(1));
% Use initial bracket in convergence test
fa = feval(fun,x0(1));
fb = feval(fun,x0(2));
fref = max([abs(fa) abs(fb)]);
% Use max f in convergence test
x = x0(1) + 0.5*(x0(2)-x0(1));
% One bisection step for initial guess
k = 0; maxit = 15;
% Current and max iterations
while k <= maxit
k = k + 1;
[f,dfdx] = feval(fun,x);
%
Returns f( x(k-1) ) and f( x(k-1) )
dx = f/dfdx;
x = x - dx;
if verbose, fprintf(%3d %12.3e %12.3e %18.14f\n,k,f,dfdx,x); end
if ( abs(f/fref) < feps ) | ( abs(dx/xref) < xeps ), r = x; return; end
end
warning(sprintf(root not found within tolerance after %d iterations\n,k));

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 6: Finding the Roots of f (x) = 0

627 Implement the secant method using Algorithm 6.5 and Equation (6.13). Test your program
by re-creating the results in Example 6.10. What happens if 10 iterations are performed?
Replace the formula in Equation (6.13) with


(xk xk1 )
xk+1 = xk f (xk )
,
f (xk ) f (xk1 ) +
where is a small number on the order of m . How and why does this change the results?
Partial Solution: The demoSecant function listed below implements Algorithm (6.5) using
Equation (6.13). The f (x) function, Equation 6.3, is hard-coded into demoSecant. Note also
that demoSecant performs ten iterations without checking for convergence.
function demoSecant(a,b);
% demoSecant Secant method for finding the root of f(x) = x - x^(1/3) - 2 = 0
%
Implement Algorithm 6.5, using Equation (6.13)
%
% Synopsis:
demoSecant(a,b)
%
% Input:
a,b = initial guesses for the iterations
%
% Output:
print out of iterations; no return values.
% copy
xk
=
xkm1 =
fk
=
fkm1 =

initial guesses to local variables


b;
% x(k)
a;
% x(k-1)
fx3(b);
% f( x(k) )
fx3(a);
% f( x(k-1) )

fprintf(\nSecant method: Algorithm 6.5, Equation (6.13) \n);


fprintf( n
x(k-1)
x(k)
f( x(k) )\n);
fprintf(%3d %12.8f %12.8f %12.5e\n,0,xkm1,xk,fk);
for n=1:10
x = xk - fk*( xk-xkm1 )/( fk - fkm1);
% secant formula for updating the root
f = fx3(x);
fprintf(%3d %12.8f %12.8f %12.5e\n,n,xk,x,f);
xkm1 = xk; xk = x;
% set-up for next iteration
fkm1 = fk; fk = f;
end

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Finding the Roots of f (x) = 0

Running demoSecant with an initial bracket of [3, 4] (the same bracket used in Example 6.10)
gives
>> demoSecant(3,4)
Secant
n
0
1
2
3
4
5
6
7

method: Algorithm 6.5, Equation (6.13)


x(k-1)
x(k)
f( x(k) )
3.00000000
4.00000000
4.12599e-01
4.00000000
3.51734262 -3.45547e-03
3.51734262
3.52135125 -2.43598e-05
3.52135125
3.52137971
1.56730e-09
3.52137971
3.52137971 -8.88178e-16
3.52137971
3.52137971 -2.22045e-16
3.52137971
3.52137971
0.00000e+00
3.52137971
3.52137971
0.00000e+00

Warning: Divide by zero.


> In /werk/MATLAB_Book/SolutionManual/roots/mfiles/demoSecant.m at line 22
8
3.52137971
NaN
NaN
9
NaN
NaN
NaN
10
NaN
NaN
NaN

The secant method has fully converged in 6 iterations. Continuing the calculations beyond
convergence gives a oating point exception because f (xk ) f (xk1 ) = 0 in the denominator
of Equation (6.13). In general, it is possible to have f (xk ) f (xk1 ) = 0 before the secant
iterations reach convergence. Thus, the oating point exception exposed by demoSecant should
be guarded against in any implementation of the secant method.
Implementing the x suggested in the problem statement is left as an exercise for the reader.

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 6: Finding the Roots of f (x) = 0

633 Write an m-le function to compute h, the depth to which a sphere of radius r, and specic
gravity s, oats. (See Example 6.12 on page 281.) The inputs are r and s, and the output is
h. Only compute h when s < 0.5. The s 0.5 case is dealt with in the following Exercise.
If s 0.5 is input, have your function print an error message and stop. (The built-in error
function will be useful.) Your function needs to include logic to select the correct root from
the list of values returned by the built-in roots function.
Partial Solution: The floata function listed below performs the desired computations. We
briey discuss three of the key statements in floata The coecients of the polynomial are
stored in the p vector. Then
c = getreal(roots(p));

nds the real roots of the polynomial. The getreal subfunction returns only the real elements
of a vector. Using getreal is a defensive programming strategy. The sample calculation in
Example 6.12 obtained only real roots of the polynomial, so getreal would not be necessary
in that case. The
k = find(c>0 & c<r);

statement extracts the indices in the c vector satisfying the criteria 0 ck r. Then
h = c(k);

copies those roots satisfying the criteria to the h vector. No assumption is made that only
one root meets the criteria. If more than one root is found a warning message is issued before
leaving floata.
Testing of floata is left to the reader.

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Finding the Roots of f (x) = 0

10

function h = floata(r,s)
% float Find water depth on a floating, solid sphere with specific gravity < 0.5
%
% Synopsis: h = floata(r,s)
%
% Input:
r = radius of the sphere
%
s = specific gravity of the sphere (0 < s < 1)
%
% Output:
h = depth of the sphere
if s>=0.5
error(s<0.5 required in this version)
else
p = [1
-3*r
0
4*s*r^3];
% h^3 - 3*r*h + 4*s*r^3 = 0
c = getreal(roots(p));
k = find(c>0 & c<r);
% indices of elements in c such that 0 < c(k) < r
h = c(k);
% value of elements in c satisfying above criterion
end
if length(h)>1, warning(More than one root found);

end

% ==============================
function cr = getreal(c)
% getreal Copy all real elements of input vector to output vector
%
% Synopsis: cr = getreal(c)
%
% Input: c = vector of numerical values
%
% Output cr = vector of only the real elements of c
%
cr = [] if c has only imaginary elements
n = 0;
for k=1:length(c)
if isreal(c(k))
n = n + 1;
cr(n) = c(k);
end
end
if n==0, cr = []; warning(No real elements in the input vector);

end

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Selected Solutions for Exercises in

Numerical Methods with Matlab:


Implementations and Applications
Gerald W. Recktenwald
Chapter 7
A Review of Linear Algebra

The following pages contain solutions to selected end-of-chapter Exercises


from the book Numerical Methods with Matlab: Implementations and
c 2000, Prentice-Hall, Upper
Applications, by Gerald W. Recktenwald, 
c 2000 Gerald W. Recktenwald. The
Saddle River, NJ. The solutions are 
PDF version of the solutions may be downloaded or stored or printed only
for noncommercial, educational use. Repackaging and sale of these solutions
in any form, without the written consent of the author, is prohibited.
The latest version of this PDF le, along with other supplemental material
for the book, can be found at www.prenhall.com/recktenwald.

A Review of Linear Algebra

7.3 Manually compute C = AB for




1 1
A=
2 3


B=

3 1
2
1

What is the relationship between A and B?.


Solution: Using Algorithm 7.6 to compute the elements of AB as an inner product between rows
of A and columns of B gives


 

1 1
3 1
(1)(3) + (1)(2) (1)(1) + (1)(1)
AB =
=
2 3 2
1
(2)(3) + (3)(2) (2)(1) + (3)(1)

(3 2)
=
(6 6)

 
(1 + 1)
1
=
(2 + 3)
0


0
1

Since, AB = I then B = A1 . Or, if you prefer, A = B 1 .


Alternatively, we can use Algorithm 7.5 to produce the same result. When we manually apply
Algorithm 7.5 we merely proceed down the rows of the result matrix. To make the organization of
Algorithm 7.5 obvious, we can separately compute each column of the result matrix. Though this
helps to visualize the algorithm, it tends to make for hand calculations that take up more space.
Nonetheless, we show how it can be done. The rst column of AB is


 
 
  
1 1
3
(1)(3) + (1)(2)
32
1
=
=
=
AB(:,1) =
2 3 2
(2)(3) + (3)(2)
66
0
The second column of AB is


 
 
  
1 1
3 1
(1)(1) + (1)(1)
1 + 1
0
AB(:,2) =
=
=
=
2 3 2
1
(2)(1) + (3)(1)
2 + 3
1
Reassembling the columns of AB gives AB = I, as before.
7.11 The trace of square matrix A is usually denoted tr(A), and is dened as the sum of the
diagonal elements of A.
n

aii
tr(A) =
i=1

Write a one-line Matlab expression to compute the trace of a matrix, A. Do not use any for...end
loops in your expression.
Solution: trA = sum(diag(A))

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 7: A Review of Linear Algebra

7.14 Write an m-le function (say, matVecCol) that evaluates a matrix-vector product (vector on
the right) using the column view, Algorithm 7.1, and only one for...end loop. This is achieved
by replacing the inner loop of Algorithm 7.1 with a single line of Matlab code that uses colon
notation. Test your function by comparing the output with A*x for random, but compatible, A and
x.
Typographical Error: In Algorithm 7.1, the statement initialize b = zeros(n, 1) should be
initialize b = zeros(m, 1)
Partial Solution: The matVecCol function is listed below. Note that the initialization statement y = zeros(m,1); is required since y must already be dened to evaluate the expression y =
x(j)*A(:,j) + y when j=1. Testing of matVecCol is left for the reader.
function y =
% matVecCol
%
% Synopsis:
%
% Input:
%
%

matVecCol(A,x)
Matrix-vector product as a linear combination of columns of A
y = matVecCol(A,x)
A,x = compatible matrix and column vector
y = A*x

[m,n] = size(A);
[mx,nx] = size(x);
if mx~=n
error(sprintf(A and x are incompatible: A is %d by %d
size(A),size(x)));
end

and x is %d by %d\n,...

y = zeros(m,1);
% initialization required
for j=1:n
y = x(j)*A(:,j) + y;
end

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

A Review of Linear Algebra

7.21 Write a rowScale function that uses a single for...end loop to perform the diagonal scaling
of a matrix. The function denition should be
function B = rowScale(A,d)

where A is the matrix to be scaled, d is a vector of scale factors. (See Example 7.6, page 330.) The
single loop is possible with judicious use of colon wild cards. Before performing any calculations test
to make sure the dimensions of A and d are compatible.
Partial Solution: The rowScale function is listed below. Testing is left to the reader.
function B = rowScale(A,d)
% rowScale Scale the rows of a matrix with the elements of a vector
%
% Synopsis: B = rowScale(A,d)
%
% Input:
A = m-by-n matrix
%
d = m-by-1 (column) vector
%
% Output: B = m-by-n matrix obtained by multiplying all elements in row i
%
of matrix A by d(i). In other words, B = diag(d)*A
[m,n] = size(A);
if length(d)~=m, error(d and A not compatible);
% --- loop over rows of A
for i=1:m
B(i,:) = d(i)*A(i,:);
end

end

scalar times a row vector

7.25 (1) Dene a matrix with columns given by the vectors in equation (7.18). Use the rank
function to determine the numbers of linearly independent columns vectors in the matrix.
Partial Solution: Since rank(A) = 3, A has three linearly independent columns. A is said to be
full rank.

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Selected Solutions for Exercises in

Numerical Methods with Matlab:


Implementations and Applications
Gerald W. Recktenwald
Chapter 8
Solving Systems of Equations

The following pages contain solutions to selected end-of-chapter Exercises


from the book Numerical Methods with Matlab: Implementations and
c 2000, Prentice-Hall, Upper
Applications, by Gerald W. Recktenwald, 
c 2000 Gerald W. Recktenwald. The
Saddle River, NJ. The solutions are 
PDF version of the solutions may be downloaded or stored or printed only
for noncommercial, educational use. Repackaging and sale of these solutions
in any form, without the written consent of the author, is prohibited.
The latest version of this PDF le, along with other supplemental material
for the book, can be found at www.prenhall.com/recktenwald.

Solving Systems of Equations

8.6 Manually solve QRx = b for x where



1/ 2
Q = 0
1/ 2


0 1/ 2
1
0
0 1/ 2

R=

1 1 1
2 0 1 1
0 0 1

b = 2 2
4

Hint: Take advantage of the properties of Q identied in the preceding problem.


Solution: Before any detailed (i.e. element-by-element) computations are performed, manipulate
the given equation as products of matrices and vectors. From Exercise 8.3 we know that QT Q = I,
so that QT = Q1 , and Q is an orthogonal matrix.
Multiplying both sides of QRx = b by QT and simplifying gives
QT QRx = QT b

Rx = QT b

For convenience, let z = QT b (z is a 3 1 column vector). If the z vector is known, we can solve
Rx = z for z with backward substitution. Given the preceding manipulations we can obtain an
easy solution to QRx = b with the following two steps
1. Evaluate z = QT b
2. Solve Rx = z with backward substitution
This completes the solution strategy. All that remains is performing the computations.
Use the row view of the matrix-vector product to evaluate QT b




2/ 2 +
2
6/ 2
0 + 4/ 2
1/ 2 0 1/ 2

1
0 2 2 =
z = QT b = 0
0+ 2 2 + 0 = 2 2
4
1/ 2 0 1/ 2
2/ 2 + 0 + 4/ 2
2/ 2
Next solve


6/ 2
1 1 1
x1
2 0 1 1 x2 = 2 2
x3
0 0 1
2/ 2

with backward substitution. For convenience, rst divide through by the factor of



6/ 2
1 1 1 x1
6/2
3
0 1 1 x2 = 1 2 2 = 2 = 2
2 2/2
0 0 1 x3
2/2
1

Work from x3 up to x1 (backward substitution):


x3 = 1
x2 + x3 = 2
x1 + x2 + x3 = 3

= x2 = 2 x3 = 1
= x1 = 3 x2 x3 = 1

Therefore the solution is x = [1, 1, 1]T . The following Matlab statements double-check the manual
solution. First, dene the Q, R, and b vectors as given
c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 8: Solving Systems of Equations


>> s2 = sqrt(2);
>> Q = [1/s2 0 -1/s2; 0 1 0; 1/s2 0 1/s2]
Q =
0.7071
0
-0.7071
0
1.0000
0
0.7071
0
0.7071
>> R = s2*[1 1 1; 0 1 1; 0 0 1]
R =
1.4142
1.4142
1.4142
0
1.4142
1.4142
0
0
1.4142
>> b = [2; 2*s2; 4]
b =
2.0000
2.8284
4.0000

As a check, verify that QT Q = I


>> Q*Q - eye(3)
ans =
1.0e-15 *
-0.2220
0
0.0224

0
0
0

0.0224
0
-0.2220

Now, obtain the solution by computing z, and then computing x by backward substitution.
>> z = Q*b
z =
4.2426
2.8284
1.4142
>> x(3) = z(3)/R(3,3)
x =
0
0

1.0000

>> x(2) = ( z(2) - R(2,3)*x(3) ) / R(2,2)


x =
0
1.0000
1.0000
>> x(1) = ( z(1) - R(1,2)*x(2) - R(1,3)*x(3) ) / R(1,1)
x =
1.0000
1.0000
1.0000
>> x = x(:)
x =
1.0000
1.0000
1.0000

convert x to column vector

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Solving Systems of Equations

We used to the most general form of the backward substitution steps, and did not exploit the fact
that all of the upper triangular elements of R are equal to one. Conversion of x from a row vector
to a column vector with x = x(:) is necessary because the x was rst created as a row vector with
the statement x(3) = z(3)/R(3,3).
8.12 Starting with the code in the GEshow function, develop a GErect function that performs
Gaussian Elimination only (no backward substitution) for rectangular (mn) matrices. The GErect
the triangularized coecient matrix, and b, the corresponding right hand
function should return A,
side vector. Use the GErect function to solve Exercise 11.
Partial Solution: The prologue and partial code for the GErect function is shown below. The
only substantial dierence between GEshow and GErect is that GErect does not perform backward
substitution.
function [At,bt] = GErect(A,b,ptol)
% GErect Gauss elimination for rectangular coefficient matrices
%
No pivoting is used.
%
% Synopsis: [At,bt] = GErect(A,b)
%
[At,bt] = GErect(A,b,ptol)
%
% Input:
A,b = coefficient matrix and right hand side vector
%
ptol = (optional) tolerance for detection of zero pivot
%
Default: ptol = 50*eps
%
% Output: At = triangularized coefficient matrix obtained by elimination
%
bt = right hand side vector transformed by the same row
%
operations necessary to obtain At
if nargin<3, ptol = 50*eps; end
[m,n] = size(A);
nb = n+1;
Ab = [A b];
% Augmented system
fprintf(\nBegin forward elimination with Augmented system:\n);

disp(Ab);

... more code goes here


At = Ab(:,1:n);

bt = Ab(:,nb);

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 8: Solving Systems of Equations

8.16 Write an lsolve function to solve Ax = b when A is a lower triangular matrix. Test your
function by comparing the solutions it obtains with the solutions obtained with the left division
operator.
Partial Solution: The lsolve function is listed below. The reader is left to complete the Exercise
by devising appropriate tests for lsolve.
function x = lsolve(L,b)
% lsolve solves the lower triangular system Lx = b
%
% Synopsis:
x = lsolve(L,b)
%
% Input:
L = lower triangular coefficient matrix
%
b = right hand side vector
%
% Output:
x = solution vector
[m,n] = size(L);
if m~=n, error(L matrix is not square); end
x = zeros(n,1);
% preallocate x for speed
x(1) = b(1)/L(1,1);
% begin forward substitution
for i=2:n
x(i) = (b(i) - L(i,1:i-1)*x(1:i-1))/L(i,i);
end

8.21 (3) The inverse matrix A satises AA1 = I. Using the column view of matrixmatrix
multiplication (see Algorithm 7.5 on page 327) we see that the j th column of A1 is the vector x
such that Ax = e(j) , where e(j) is the j th column of the identity matrix (e.g., e3 = [0, 0, 1, . . . , 0]T ).
By solving Ax = e(j) for j = 1, . . . , n the columns of A1 can be produced one at a time.
(a) Write a function called invByCol that computes the inverse of an n n matrix one column at
a time. Use the backslash operator to solve for each column of A1 .
(b) Use the estimates in Table 8.1 to derive an order-of-magnitude estimate for how the op count
of invByCol depends on n for an n n matrix.
(c) Verify the estimate derived in part (b) by measuring the op count of invByCol for matrices
of increasing size. Use A = rand(n,n) for n = 2, 4, 8, 16, 32, . . . , 128. Compare the op count of
invByCol with those of the built-in inv command. Note that the order-of-magnitude estimate
will only hold as n becomes large. Users of Matlab version 6 will not be able to use the flops
function to measure the ops performed by inv. In that case, use the estimate that matrix
inversion can be performed in O(n3 ) ops.
Solution (a): A is given. The objective is to solve a sequence of problems Ax = e(j) , j = 1, . . . , n.
Each x becomes a column of A1 . Doing so requires a loop, and a way to dene e(j) . The following
statements do the job
for j=1:n
e = zeros(n,1);
Ai(:,j) = A\e;
end

e(j) = 1;

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Solving Systems of Equations

where n is the number of rows in A. The expression Ai(:,j) = A\e stores the solution to Ax = e(j)
in the j th column of Ai. The eciency of the loop can be improved by preallocating memory for
Ai, and using a xed zero vector z = zeros(n,1) instead of creating a new vector on each pass
through the loop. These improvements, along with provisions for input and output and some basic
error checking are incorporated into the invByCol function listed below.
function Ai = invByCol(A)
% invByCol Compute matrix inverse of a matrix by columns
%
% Synopsis: Ai = invByCol(A)
%
% Input:
A = square (n by n) matrix
%
% Output:
Ai = inverse of A, if it exists
[m,n] = size(A);
if m~=n, error(Inverse is defined only for square matrices);
Ai = zeros(n,n);
z = zeros(n,1);
for j=1:n
e = z; e(j) = 1;
Ai(:,j) = A\e;
end

%
%

pre-allocate for speed


temporary vector

%
%

reset column of I
Solve for jth column of A^(-1)

end

A simple test of invByCol is


>> A = rand(5,5); Ai = invByCol(A); E = Ai*A - eye(5)
E =
1.0e-15 *
-0.1110
-0.1661
-0.2774
-0.0659
-0.1029
-0.0513
0.2220
0.0081
-0.0912
-0.1724
0.1372
0.1194
0.4441
0.3129
0.0386
-0.0205
-0.0691
-0.1924
0
0.0978
-0.0833
0.0571
0.0031
0.0324
0
>> norm(A,1)
ans =
3.3992
>> norm(E,1)
ans =
9.2514e-16

Since E1  A1 and A is reasonably well-conditioned (How do we know?), the invByCol function
appears to be working. Note that the L1 norm is chosen for eciency. Both the L and L2 norms
would give equivalent results. The L norm would take less ops than the L1 norm. Both L1
and L norms are signicantly more ecient than the L2 norm. For a 5 5 matrix the eciency
dierences are irrelevant, however.
Solution (b): Each solution of Ax = e(j) takes O(n3 /3) ops. There are n columns of A1 so the
invByCol function takes n O(n3 /3) = O(n4 /3) ops for an n n matrix A. This is an expensive
way to compute A1 .
Solution (c): The demoInvByCol function (listed below) measures the ops performed by the
invByCol function and the built-in inv function. These functions are applied to a sequence of
c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 8: Solving Systems of Equations

random n n matrices is generated for n = [2 4 8 16 32 64 128]. The elements of matrix A are


unimportant as long as A is nonsingular. It turns out that the matrices generated by the built-in
rand function are rarely singular. The op counts are measured with the built-in flops function.
Note that these measurements will yield zero ops for Matlab version 6 and later. Thus, the
demoInvByCol function is useful only to users of Matlab version 5 and earlier.
The op count for each n is saved for plotting and analysis. The powfit function is used to obtain
the least squares t (see Fitting Lines to Apparently Nonlinear Functions in Chapter 9) to
f = c1 nc2
where f is a vector of measured op counts and n is the vector of matrix dimensions. The c2
exponent should be 4 for the invByCol function because the op count grows as O(4). (See solution
to part (b), above.) For the built-in inv function the c2 exponent should be 3 because the inv
function computes the inverse via LU factorization, op count grows as O(3).
The n(3:end) and f(n:end) vectors are passed to powfit. The 3:end index subexpression selects
the third through last elements of the vector. This improves the estimate of c2 because the order of
magnitude estimates of the op counts only applies for large n.

function demoInvByCol
% demoInvByCol Measure flop count behavior of invByCol
% --- Count flops for invByCol and built-in inv functions
n = [2 4 8 16 32 64 128];
% Sizes of problems to run
for i=1:length(n)
A = rand(n(i),n(i));
flops(0);
Ai = invByCol(A); fcol(i) = flops;
flops(0);
Ai = inv(A);
fInv(i) = flops;
end
% --- Use least squares fits to obtain exponent of flops relationship
c = powfit(n(4:end),fcol(4:end));
cinv = powfit(n(4:end),fInv(4:end));
% --- Evaluate least squares fits and plot
nfit = n(4:end);
fcolfit = c(1)*nfit.^c(2);
finvfit = cinv(1)*nfit.^cinv(2);
loglog(n,fcol,o,nfit,fcolfit,-,n,fInv,v,nfit,finvfit,-)
legend(invByCol flops,fit,inv flops,fit,2)
xlabel(Number of unknowns);
ylabel(flops);
% --- Print summary
fprintf(\nFlop counts:\n\n);
fprintf(
n
invByCol
inv\n);
for i=1:length(n)
fprintf(
%4d
%10d
%10d\n,n(i),fcol(i),fInv(i));
end
fprintf( exponent
O(%3.1f)
O(%3.1f)\n,c(2),cinv(2));

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Solving Systems of Equations


function c =
% expfit
%
% Synopsis:
%
% Input:
%
% Output:

powfit(x,y)
Least squares fit of data to y = c1*x^c2
c = powfit(x,y)
x,y = vectors of independent and dependent variable values
c = vector of coefficients: y = c(1)*x^c(2)

if length(y)~=length(x),

error(Dimensions of x and y are not compatible);

ct = linefit(log(x(:)),log(y(:)));
c = [exp(ct(2)) ct(1)];

%
%

end

Line fit to transformed data


Extract parameters from transformation

Running demoInvByCol produces the following output and the plot below.
>> demoInvByCol
Flop counts:
n
2
4
8
16
32
64
128
exponent

invByCol
96
768
7040
76128
952768
13163520
194685952
O(3.8)

inv
51
242
1412
9598
70942
545040
4276376
O(2.9)

The invByCol function is clearly less ecient than the built-in inv function. The measured ops
exponent for the inv function is close to the theoretical value of 3. The measured ops exponent
for invByCol is somewhat less than the expected value of 4. The discrepancies are likely caused by
the relatively small values of n used, and the way that Matlab counts the ops for the backslash
operator.
9

10

invByCol flops
fit
inv flops
fit

10

10

flops

10

10

10

10

Exercise 821. Flop counts


for invByCol and inv.

10

10
0
10

10

10

10

Number of unknowns

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 8: Solving Systems of Equations

Extra Credit: The most costly phase of invByCol is repeatedly solving Ax = e(j) . Rewrite the
invByCol function to use LU factorization to reduce the computational work. Factor matrix A once,
then (inside a loop) use triangular solves to produce each column of I. Compare the op count of
your new function with the original version of invByCol.
The extra credit solution is implemented in the invByColLU and demoInvByColLU functions (neither
are listed here). Running demoInvByColLU gives
>> demoInvByColLU
Flop counts:
n
2
4
8
16
32
64
128
exponent

invByCol
100
752
7168
77216
950400
13186432
194873088
O(3.7)

inv
51
242
1444
9594
70836
545124
4275098
O(2.9)

invByColLU
35
226
1588
11816
90960
713376
5649728
O(3.0)

The invByColLU function obtains the exact ops exponent value of 3 that is predicted by the order
of magnitude work estimates. The built-in inv function uses the ideas embodied in invByColLU to
compute A(1) .
8.25 An alternative way to resolve the singularity in the 3 3 coecient matrix of Example 8.5 is
to modify the elements of the matrix. Write a trivial equation involving vb , vc , and vd that has the
solution vd = 0. Use this equation to replace the equation for vd in the 3 3 system in Example 8.5.
What is the value of Vout for R1 = R3 = R4 = R5 = 10 k, R2 = 20 k and Vin = 5 V .
Partial Solution: The trivial equation with the solution vd = 0 is (0)vb + (0)vc + (1)vd = 0, or
vd = 0.
8.33 Use the pumpCurve function developed in Exercise 32 to study the eect of perturbing the
input data. Specically, replace the second h value, h = 114.2, with h = 114, and re-evaluate
the coecients of the cubic interpolating polynomial. Let c be the coecients of the interpolating
polynomial derived from the perturbed data, and let c be the coecients of the polynomial derived
from the original data. What is the relative dierence, (
ci ci )/ci , in each of the polynomial
coecients? Evaluate and plot h(q) for the two cubic interpolating polynomials at 100 data points
in the range min(q) q max(q). What is the maximum dierence in h for the interpolants derived
from the original and the perturbed data? Discuss the practical signicance of the eect perturbing
the data on the values of c and the values of h obtained from the interpolant.
Partial Solution: The computations are carried out in pumpPerturb (not listed here). Running
pumpPerturb gives the following output and plot..
>> pumpPerturb
Coefficients of cubic interpolant in descending powers of q:
i
1
2

c(i)
-1.1870738e+10
1.0361305e+07

ct(i)
-1.3978775e+10
1.5209790e+07

percent diff
17.8
46.8

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

10

Solving Systems of Equations


3
4

-7.8023933e+03
1.1568850e+02

-1.0627163e+04
1.1592460e+02

Maximum difference of h values =


Condition numbers: kappa(A) =

36.2
0.2

0.253 (m) occurs at q =


2.7e+10;
kappa(At) =

3.89e-04
2.7e+10

c(i) are the coecients of the cubic polynomial derived from the unperturbed data. ct(i) are the
coecients derived from the perturbed data. Although the coecients have very large dierences in
magnitude, the values of the interpolants have a maximum dierence of only 0.25 m in head. The
perturbation has no signicant eect on the condition number of the Vandermonde system.
120
Data
Original interpolant
Perturbed interpolant
point of max difference
115

Head (m)

110

105

100

Exercise 833. Interpolants


from original and perturbed h
data.

95

90

0.5

1
3

Flow rate (m /s)

1.5
-3

x 10

c 2000, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Selected Solutions for Exercises in

Numerical Methods with Matlab:


Implementations and Applications
Gerald W. Recktenwald
Chapter 9
Least Squares Fitting
of a Curve to Data

The following pages contain solutions to selected end-of-chapter Exercises


from the book Numerical Methods with Matlab: Implementations and
c 2001, Prentice-Hall, Upper
Applications, by Gerald W. Recktenwald, 
c 2001 Gerald W. Recktenwald. The
Saddle River, NJ. The solutions are 
PDF version of the solutions may be downloaded or stored or printed only
for noncommercial, educational use. Repackaging and sale of these solutions
in any form, without the written consent of the author, is prohibited.
The latest version of this PDF le, along with other supplemental material
for the book, can be found at www.prenhall.com/recktenwald.

Least Curve Fitting

9.3 Lipson and Sheth (Statistical Design and Analysis of Engineering Experiments, 1973, McGrawHill, p. 385) give data on the wear of a particular journal bearing as a function of operating
temperture. Their data are contained in the bearing.dat le in the data directory of the NMM
Toolbox. Use the linefit function to t bearing wear as a function of temperature. Plot a comparison of the data and the curve t on the same axes. From this data what is the limit on bearing
temperature if the wear should not exceed 8 mg/100hr of operation?
Numerical Answer:
499.5206 C).

A plot of the t is shown below. The temperature limit is 500 C (T =

12

Wear

(mg/100 hr)

10

Plot of solution to
Exercise 93.

0
200

300

400

T ( C)

500

600

700

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 9: Least Curve Fitting

9.6 The xyline.dat le contains two columns of numbers (x and y) that are reasonably well-tted
by a line. Write an m-le function to perform the following tasks:
(a) Find the slope and intercept of the line, storing these in a vector called c. Compute the norm
of the residual of the t, r = y Ac2
(b) Create two vectors with values within 40 percent of the c1 and c2 obtained from the preceding
step; that is, create
c1t = c(1)*linspace(0.6,1.4,20);
c2t = c(2)*linspace(0.6,1.4,20);
(c) Create a matrix, R, having elements equal to the norms of the residuals of the ts using all
combinations of c1t and c2t, i.e.
R(i,j) = norm( y - (c1t(i)*x + c2t(j)) );
(d) Use the built in meshc and contour functions to create surface and contour plots with R on
the z axis, c1t on the x axis, and c2t on the y axis.
(e) Explain how the data displayed in the surface and contour plots is consistent with the theory
used to develop the c for the least squares t.
Partial Solution:
page.

Carrying out the computations in steps (a)(d) gives the plots on the next

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Least Curve Fitting


2.5
Data
Fit
2

1.5

0.5

Exercise 96. Plot (a):


Curve t.

0.5

1
0

10

15

Residual as function of c1 and c2

6
5
4
||r||32
2
1
0
3
2.5

0.1

Exercise 96. Plot (b):


Surface plot of residuals.

0.15

0.2

1.5

0.25
1

c2

0.3

c1

Residual as function of c1 and c2


2.8
2.6
2.4

c2

2.2
2

1.8

Exercise 96. Plot (c):


Contour plot of residuals.

1.6
1.4

0.26

0.24

0.22

0.2
c

0.18

0.16

0.14

0.12

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 9: Least Curve Fitting

9.7 Least squares tting problems with only one undetermined coecient lead to particularly simple
computational procedures. Derive the equations for nding the (scalar) c coecient of the following
equations assuming that x and y are known vectors of data
(a) y = c x
(b) y = c x2
(c) y = xc
For each of these t equations, write a one-line Matlab expression to compute c. Assume that
x and y are column vectors. Hint: Write the overdetermined system and then form the normal
equation.
Solution (a):

For m data pairs the overdetermined system is




y1
x1
y2
x2


.. c = ..
.
.
xm
ym

The column vector x corresponds to the coecient matrix in Equation (9.15). Form the (only one)
normal equation by multiplying both sides by xT on the left.


x1
y1

y2
x




2


x1 x2 xm . c = x1 x2 xm .

xT x c = xT y
..
..
xm

ym

Since xT x and xT y are both scalars we can directly solve for c.


c=

xT y
xT x

Translating the preceding expression to Matlab gives


>> x = ...
>> y = ...
>> c = (x*y)/(x*x)

(x and y are column vectors)

Does c = (x*x)\(x*y) return the same result?

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Least Curve Fitting

9.11 The function y = x/(c1 x + c2 ) can be transformed into a linear relationship z = c1 + c2 w with
the change of variables z = 1/y, w = 1/x. Write an xlinxFit function that calls linefit to t
data to y = x/(c1 + c2 x). Test your function by tting the following sets of data.
x
y
x
y

2.2500
2.8648

0.7000
-0.1714

Typographical Error:

2.5417
1.4936

1.0714
-0.3673

2.8333
1.0823

1.4429
-0.8243

3.1250
0.8842

1.8143
-3.1096

3.4167
0.7677

2.1857
3.7463

3.7083
0.6910

2.5571
1.4610

4.0000
0.6366

2.9286
1.0039

3.3000
0.8080

The correct form of the transformed linear relationship is z = c1 + c2 w.

Partial Solution: For the rst data set, c1 = 3.1416, c2 = 6.2832. For the second data set,
c1 = 3.1415, c2 = 6.2831.

9.19 The temperature dependence of the viscosity of a liquid can be modeled with

ln

= c1 + c2

T
+ c3
T0

T
T0

where is the viscosity, T is the absolute temperature, 0 and T0 are reference values of and T ,
and ci are curve t constants. Use the data in the H2OVisc.dat le in the data directory of the
NMM Toolbox to nd values of the ci for water with T0 = 0 C. The rst column in H20Visc.dat
is the temperature in C, the second column is the viscosity in kg/(m s). Convert the temperature
to kelvins before performing the t.
Numerical Answer:

c1 = 15.5613, c2 = 23.4078, c3 = 7.8189

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 9: Least Curve Fitting

9.23 (Adapted from P.W. Atkins, Physical Chemistry, 2nd ed., 1982, W.H. Freeman, San Francisco,
problem 27.15, p. 964) The temperature dependence of the reaction rate coecient of a chemical
reaction is often modeled by the Arrhenius equation
k = A exp(Ea /RT )
where k is the reaction rate, A is the pre-exponential factor, Ea is the activation energy, R is the
universal gas constant, and T is the absolute temperature. Experimental data for a particular
reaction yield the following results:
T (K)

773.5

786

797.5

810

810

820

834

1.63

2.95

4.19

8.13

8.19

14.9

22.2

Use a least squares t of this data to obtain values for A and Ea for the reaction. Take R =
8314J/kg/K.
Solution: Vectors of k and T are given, the scalars A and Ea are unknown. The Arrhenius
equation can be written
()
k = c1 exp(c2 x)
where c1 = A, c2 = Ea , and x = 1/(RT ). Therefore, by tting Equation () to the (k, T ) data
we obtain A and Ea . The curve t is easily performed with the expfit function developed as the
solution to Exercise 8.
The curve t for the given data is computed in the demoArrhenius function listed below. Note that
the fitArrhenius subfunction could be moved to a separate m-le so that it could be called by
other m-les or invoked directly from the command window.
Running demoArrhenius gives A = 1.8717 1013 , Ea = 2.3803 108 , and the plot on the next page.

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Least Curve Fitting


function demoArrhenius
% demoArrhenius Demonstrate least squares fit to Arrhenius reaction rate equation
%
Uses the fitArrhenius function.
Exercise 9-23
%
r
t
k

--- Store data


= 8314;
= [773.5 786 797.5 810
= [1.63 2.95 4.19 8.13

% gas constant, J/(K*kg-mol)


810 820 834];
8.19 14.9 22.2]*1e-3;

% --- Obtain fit, print parameters, and plot fit along with data
[a,ea] = fitArrhenius(k,t,r)
tf = linspace(750,840);
kf = a*exp(-ea./(r*tf));
plot(t,k,o,tf,kf,-);
xlabel(T (K));
ylabel(Reaction rate);
legend(Data,Fit,2);
% =====================================================
function [a,ea] = fitArrhenius(k,t,r)
% fitArrhenius Least squares fit to parameters of arrhenius rate equation
%
% Synopsis: [a,ea] = fitArrhenius(k,t)
%
[a,ea] = fitArrhenius(k,t,r)
%
% Input:
k = vector of reaction rate constants
%
t = vector of temperatures
%
r = (optional) gas constant; Default: r = 8314 J/(K*kg-mol)
%
% Output: a,ea = parameters in the arrhenius rate equation, k = a*exp(-ea/r/t)
%
"a" is the pre-exponential factor. ea is the activation energy.
if nargin<3, r = 8314;
c = expfit(1./(r*t),k);
a = c(1);
ea = -c(2);

end

default gas constant

J/(K*kg-mol)

0.03
Data
Fit

0.025

Reaction rate

0.02

0.015

0.01

Plot of solution to
Exercise 923.

0.005

0
750

760

770

780

790

800

810

820

830

840

T (K)

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 9: Least Curve Fitting

9.26 Write a function to t data to y = c1 x5 + c2 x3 + c3 x + c4 without calling polyfit, fitnorm, or


fitqr. Your function should take two column vectors, x and y, as input, and return the coecient
vector. It should be self-contained, i.e, it should set up and solve the overdetermined system of
equations without calling any auxiliary functions. Test your solution with the following data.
x
y

-3.0000
-4.9262

Numerical Answer:
c4 = 3.181091285.

-1.8571
-4.4740

-0.7143
-3.3136

0.4286
-2.9396

1.5714
-2.6697

2.7143
-1.3906

3.8571
-0.8669

5.0000
-3.3823

c1 = 3.116759277 103 , c2 = 6.286454564 102 , c3 = 0.3375296900,

9.32 The pdxTemp.dat le in the data directory of the NMM toolbox contains historically averaged
monthly temperatures measured at the Portland, OR airport. The le contains four columns of data.
The rst column is the number of the month (1 through 12). The second through fourth columns are
the historically averaged low, high, and average temperature, respectively, for each month. Create
a t of the average temperature to the function


(m 1)
T = c1 + c2 sin2
12
where m is the number of the month. Plot a comparison of the original data and the t function.
Hint: (1) Replicate the January data so that the input has 13 pairs of values with January at the
beginning and end of the data set, (2) create a vector of = (m 1)/12 values.
Partial Solution: The t coecients are c1 = 39.579986, c2 = 27.863363. Below is a plot of the
t and the original data.
70
Data
Fit

Average temperature (F)

65

60

55

50

45

Plot of solution to
Exercise 932.

40

35
0

10

12

14

month

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

10

Least Curve Fitting

9.37 Lipson and Sheth (Statistical Design and Analysis of Engineering Experiments, 1973, McGrawHill, p. 385) give data on nitrogen oxide (NO) emission from an internal combusition engine as a
function of humidity and atmospheric pressure. Their data are contained in the emission.dat le
in the data directory of the NMM toolbox. Obtain a multiple linear regression of this data of the
form
NO = c1 + c2 h + c3 p
where h is the humidity in grains per pound of dry air, and p is the atmospheric pressure in inches
of Mercury. What are the values of c1 , c2 and c3 ?
Numerical Answer:

c1 = 5028.913856, c2 = 5.347260274, c3 = 117.4130076.

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Selected Solutions for Exercises in

Numerical Methods with Matlab:


Implementations and Applications
Gerald W. Recktenwald
Chapter 10
Interpolation

The following pages contain solutions to selected end-of-chapter Exercises


from the book Numerical Methods with Matlab: Implementations and
c 2001, Prentice-Hall, Upper
Applications, by Gerald W. Recktenwald, 
c 2001 Gerald W. Recktenwald. The
Saddle River, NJ. The solutions are 
PDF version of the solutions may be downloaded or stored or printed only
for noncommercial, educational use. Repackaging and sale of these solutions
in any form, without the written consent of the author, is prohibited.
The latest version of this PDF le, along with other supplemental material
for the book, can be found at www.prenhall.com/recktenwald.

Interpolation

10.3 What are the condition numbers for the two Vandermonde matrices in Examples 10.4 and
10.5? How does the change in (A) relate to the dierent results obtained in Example 10.5?
Numerical Answer:

For Example 10.4, (A) = 1.0 1031 . For Example 10.5, (A) = 3.8 103 .

10.3 (2+) In Example 10.4, the coecients of the interpolating polynomial are evaluated and
printed to ve signicant digits. Evaluate the gasoline prices and the errors in the interpolant using
the truncated coecients and the following denitions: Let (yi , pi ) be the year and price in the
given tabulated data. Let pi be the price interpolated with the untruncated polynomial coecients
at the yi , and pi be the price interpolated with the truncated coecients at the yi . In the absence
of numerical errors we expect pi = pi = pi from the denition of interpolation. Compute and print
p p2 , pi , pi pi , and 
p p2 . How many digits of the c coecients need to be
pi , pi pi , 
retained in order to get p p comparable to p p ? Hint: The chop10 function in the utils
directory of the NMM toolbox will be helpful.
Partial Solution:

The original and chopped coecients are:

c(k)
3.03815522e-03
-3.02074596e+01
1.20137182e+05
-2.38896442e+08
2.37525874e+11
-9.44650495e+13

chopped c(k)
3.03820000e-03
-3.02070000e+01
1.20140000e+05
-2.38900000e+08
2.37530000e+11
-9.44650000e+13

Evaluating the errors in the original polynomial (error p), and the polynomial obtained with
chopped coecients (error pc) gives
year
1986
1988
1990
1992
1994
1996

price
133.50
132.20
138.70
141.50
137.60
144.20

error p
4.69e-02
-1.25e-02
-9.06e-02
-4.69e-02
-3.75e-02
9.69e-02

error pc
2.48e+10
2.49e+10
2.50e+10
2.51e+10
2.51e+10
2.52e+10

L2 norm of price error with original coefficients =


L2 norm of price error with chopped coefficients =

1.53e-01
6.13e+10

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 10: Interpolation

10.12 Manually compute the quadratic interpolation in Example 10.7 using instead the following
support points.
(a) T1 = 20, T2 = 30, T3 = 40
(b) T1 = 0, T2 = 10, T3 = 20
Compare the results to the interpolant using T1 = 10, T2 = 20, and T3 = 30.
Numerical Answer:
Support Points
T = 10, 20, 30
T = 20, 30, 40
T = 0, 10, 20

(22)
1.202
1.278
1.565

Dierence
0
6.3%
30%

10.14 The H2Osat.dat le in the data directory of the NMM toolbox contains saturation data for
water. Use this data and quadratic polynomial interpolation to manually compute psat in the range
30 T 35 C.
(a) Manually construct the divided-dierence table. Use the divDiffTable function to check your
calculations.
(b) Extract the coecients of the Newton interpolating polynomial from the divided dierence
table.
(c) Evaluate the interpolant at T = 32, 33, and 34 C. Verify you calculations with newtint.
Partial Solution: Three support points are needed for quadratic interpolation. The data in
H2Osat.dat is in increments of 5 C. Thus, reasonable support points for the interpolation are
either T = 25, 30, and 35, or T = 30, 35, and 40. The table below summarizes the results of the
interpolations.
support points
T = 25, 30, 35
T = 30, 35, 40

psat (32)
0.04762
0.04754

psat (33)
0.05039
0.05030

psat (34)
0.05327
0.05322

All pressures are in bar.

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Interpolation

10.18 The degree of the polynomial interpolant used by lagrint and newtint is determined by
the length of the input vectors to these functions. Suppose one wished to specify the order of the
interpolant, regardless of the length of the input data. In other words, suppose the objective was to
perform a local interpolation of degree n in a table of length m, where m > n. This requires selecting
an appropriate subset of the input data table and passing this subset to lagrint or newtint. For
example, a quadratic interpolation could be performed with
x = ...
% define tabular data
y = ...
xhat = ...
% interpolate at this value
ibeg = ...
% beginning index for support points of interpolant
yhat = newtint(x(ibeg:ibeg+2),y(ibeg:ibeg+2),xhat)

Write an m-le function called quadinterp that automatically selects an appropriate subset of the
vectors x and y, and returns the value of the quadratic interpolant using those support points. The
function denition statement for quadinterp is
function yhat = quadinterp(x,y,xhat)

The quadinterp function calls newtint to perform the interpolation. The binSearch function in
Listing 10.6 will be useful. Use your quadinterp function to generate data for smooth plot of the
glycerin viscosity data in Example 10.2.
Partial Solution: The selection of support points can be automated with the binSearch function
from Listing 10.6. The binSearch function nds the index i such that x(i) xhat x(i + 1), when
the x vector contains monotonically increasing values. The question remains: Which additional
point is used to create the three support points needed to dene the quadratic interpolant? To
avoid an index range error when i = 1, the three support pairs must be (x(1),y(1)), (x(2),y(2)),
and (x(3),y(3)). Similarly, when i = n 1 the three support pairs must be (x(n-2),y(n-2)),
(x(n-1),y(n-1)), and (x(n),y(n)). How should we choose the support points when 2 i n 2?
Suppose we an attempt to optimize the choice of support points. (This turns out to be a bad idea,
but well pursue it anyway.) Assume, for simplicity, that the x data are equally spaced, and consider
the case, as depicted in the following sketch, where xhat is closer to x(i) than x(i+1)

xi1

xi

xi+1

xi+2

Exercise 1018. Attempt at


optimal selection of support
Points

1 (x +x )
2 i i+1
c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 10: Interpolation

For this xhat a good choice of support points would seem to be (x(i-1),y(i-1)), (x(i),y(i)), and
(x(i+1),y(i+1)). On the other hand, if xhat > (x(i) + x(i + 1))/2 a good choice of support points
would seem to be (x(i),y(i)), (x(i+1),y(i+1)), and (x(i+2),y(i+2)). The quadInterpBad function listed on the next page here uses this logic The demoQuadInterp function uses quadInterpBad
and quadInterp functions to interpolate the glycerin viscosity data. Runninng demoQuadInterp
gives the following plot.
12
Data
Quadratic interpolant
Discontinuous interpolant
10

(Pa s)

Exercise 1018. Two


versions of piecewise quadratic
interpolation

10

15

20

25

T ( C)

30

35

40

45

50

The problem with our attempt to optimize the choice of the support points is that the support
points change in the middle of an interval, which causes the interpolant to be discontinuous. For
this problem it is better to change the support points only at the ends of the intervals at the
support points. The code to do this is actually simpler than the code in quadInterpBad. A better
implementation of quadInterp involves choosing ibeg=i for all cases except when i=length(x)-1.
Converting the code in quadInterpBad is left for the reader. On the next page are listings of the
demoQuadInterp and quadInterpBad functions.
An explicit loop is used to return a vector of interpolant values (yhat) if the input xhat is a
vector. This is necessary since the binSearch function cannot be vectorized. The scalarQuadInterp
subfunction performs the quadratic interpolation for a single value of xhat.

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Interpolation
function demoQuadInterp
% demoQuadInterp Piecewise quadratic interpolation of glycerin data
%
Exercise 10-18
% --- Read data from glycerin.dat
[t,D] = loadColData(glycerin.dat,5,7);
mu = D(:,2);
% viscosity is in second column of file
% --- Evaluate interpolants
ti = linspace(min(t),max(t));
mui = quadInterp(t,mu,ti);
mu2 = quadInterpBad(t,mu,ti);
plot(t,mu,ko,ti,mui,b-,ti,mu2,r--)
legend(Data,Quadratic interpolant,Discontinuous interpolant);
xlabel(T (^\circ C));
ylabel(\mu (Pa\cdot s));

function yhat = quadInterpBad(x,y,xhat)


% quadInterpBad Discontinuous piecewise quadratic interpolation
%
in a table of (x,y) data.
Exercise 10-18
%
% Synposis: yhat = quadInterpBad(x,y,xhat)
%
% Input:
x,y = vectors containing the tabulated data
%
xi = value of x at which function y = f(x) is desired
%
% Output:
yi = value of y at xi obtained by quadratic interpolation
% --- Allow vector of inputs: use explicit loop over all elements of xhat
yhat = zeros(size(xhat));
for k=1:length(xhat)
yhat(k) = scalarQuadInterp(x,y,xhat(k));
end
% =============
function yhat = scalarQuadInterp(x,y,xhat)
% scalarQuadInterp
Piecewise quadratic interpolation at a single point
%
% Use hueristic choice of three support points. Let i be the index
% returned from binSearch, i.e. x(i) <= xhat <= x(i+1). If i is in
% the range 2 <= i <= n-1, and if xhat is less than the midpoint of
% [x(i), x(i+1)], then choose support points [i-1, i, i+1]. Otherwise
% choose support points [i, i+1, i+2].
i = binSearch(x,xhat);
% Find appropriate data pair
if i==1
ibeg=1;
elseif i==length(x)-1
ibeg=length(x)-2;
% Avoid index range error
elseif xhat < (x(i)+0.5*(x(i+1)-x(i)))
% hueristic choice of support points
ibeg = i-1;
else
ibeg = i;
end
yhat = newtint(x(ibeg:ibeg+2),y(ibeg:ibeg+2),xhat); % Evaluate interpolant

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 10: Interpolation

10.21 The classic example of polynomial wiggle is the so-called Runge function
r(x) =

1
,
1 + 25x2

named after German mathematician Carl Runge (18561927), who used this function to study the
behavior of high-degree polynomial interpolation. Write a function m-le called runge to perform
the following tasks.
(a) Compute n equally spaced xk values (k = 1, . . . , n) on the interval 1 x 1. Let n be an
input parameter to runge.
(b) Evaluate r(xk ) from Equation (10.55) for k = 1, . . . , n.
(c) Use the n pairs of (xk , r(xk )) values to dene a degree n 1 polynomial interpolant, Pn1 .
Evaluate the interpolant at x
j , j = 1, . . . , 100 points in the interval 1 x 1.
xj , Pn1 (
xj ), and the true
(d) Plot a comparison of the original data, (xk , r(xk )), the interpolant, (
xj ). Use open circles for r(xk ), a dashed
value of the function at the interpolating points (
xj , r(
xj ), and a solid line for r(
xj ).
line for Pn1 (
x)2 .
(e) Print the value of r(
x) Pn1 (
x)2 as n is
Run your runge function for n=5:2:15, and discuss the behavior of r(
x) Pn1 (
increased.
Partial Solution: The runge function is listed below. Running the function and interpretting
the results are left to the reader.
function e = runge(n)
% runge Uniformly spaced interpolation of the Runge function. Exercise 10-21
%
% Synopsis: runge(n)
%
% Input: n = number of points to define the polynomial interpolant.
%
The polynomial is of degree n-1
%
% Output: e = L2 norm of error for the interpolant evaluated at
%
100 points in the interval -1 <= x <= 1
x = linspace(-1,1,n);
r = 1./(1+25*x.^2);

%
%

Define n support points (x,r(x))


Exact value of Runge function

xhat = linspace(-1,1);
yhat = newtint(x,r,xhat);
rhat = 1./(1+25*xhat.^2);

%
%
%

100 equally-spaced points


Polynomial interpolant of degree n-1
Exact r(x) at xhat

plot(x,r,o,xhat,yhat,--,xhat,rhat,-);
e = norm(yhat-rhat);

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Interpolation

10.24 The stdatm.dat in the data directory of the NMM toolbox gives the properties of the socalled standard atmosphere as a function of elevation above sea level. Write a routine that uses
piecewise linear interpolation to return the values of T , p, and at any elevation in the range of the
table. Write your m-le function so that it does not read the data from this le when it is executed;
that is, store the data in matrix variables in your m-le. What are the values of T , p, and at
z = 5500 m and z = 9023 m? Plot the variation of T and in the range 0 z 15 km.
Numerical Answer:
T ( C)
17.47
43.56

z (m)
5500
9023

p (Pa)
54050
30701

(kg/m3 )
0.7364
0.4659

10.32 Plot the spline interpolant of the following data:


xi
yi

0.2
0.5535

0.6
1.0173

1.0
1.0389

1.4
0.8911

On the same plot, compare the spline interpolant to y =


create the data in the table.

1.8
0.7020

2.2
0.5257

12.5 x exp( 1.5 x), which was used to

Partial Solution: Below is a plot of the sample data, the spline interpolant, and the function used
to create the sample data. Lacking any information about the slope at the endpoints, the not-a-knot
end conditions were used to dene the spline.

1.2
Data
notaknot spline
Original function

1.1

0.9

0.8

0.7

Plot of solution to
Exercise 1032.

0.6

0.5
0

0.5

1.5

2.5

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Selected Solutions for Exercises in

Numerical Methods with Matlab:


Implementations and Applications
Gerald W. Recktenwald
Chapter 11
Numerical Integration

The following pages contain solutions to selected end-of-chapter Exercises


from the book Numerical Methods with Matlab: Implementations and
c 2001, Prentice-Hall, Upper
Applications, by Gerald W. Recktenwald, 
c 2001 Gerald W. Recktenwald. The
Saddle River, NJ. The solutions are 
PDF version of the solutions may be downloaded or stored or printed only
for noncommercial, educational use. Repackaging and sale of these solutions
in any form, without the written consent of the author, is prohibited.
The latest version of this PDF le, along with other supplemental material
for the book, can be found at www.prenhall.com/recktenwald.

Numerical Integration

11.2 Write a polyInt function that uses the built-in polyval function to evaluate the denite
integral of a polynomial. The inputs to polyInt should be a vector of polynomial coecients and
the lower and upper limits of integration. Test your function by evaluating the two integrals in the
preceding exercise.
Update for Matlab version 6: Version 6 includes a polyint function that comes close to solving
this Exercise. To avoid the name clash, the solution presented here is to develop a polyIntegral
function.
Partial Solution:

A correct implementation of polyIntegral gives

>> I1 = polyIntegral([1 1 1],-pi/2,pi)


I1 =
20.0408
>> I1exact = (3/8)*pi^3 + (3/8)*pi^2 + (3/2)*pi;
>> err1 = I1 - I1exact
err1 =
0
>> I2 = polyIntegral([1 0 0 -1],sqrt(3),-5)
I2 =
160.7321
>> I2exact = ( (-5)^4/4 + 5 ) - ( 9/4 - sqrt(3) );
>> err2 = I2 - I2exact
err2 =
0

How would the built-in polyint (Matlab version 6) function be used to evaluate the denite
integral of a polynomial?

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 11: Numerical Integration

11.3 Use the symbolic capability of the Student Edition of Matlab or the Symbolic Mathematics
Toolbox, to nd the denite integral of the generalized humps function
f (x) =
Solution:

1
1
+
+ c5
(x c1 )2 + c2
(x c3 )2 + c4

The following Matlab session requires a version of the Symbolic Mathematics Toolbox.

>> syms a b c1 c2 c3 c4 c5 f x
>> f = 1/( (x-c1)^2 + c2 ) + 1/( (x-c3)^2 + c4 ) + c5
f =
1/((x-c1)^2+c2)+1/((x-c3)^2+c4)+c5
>> g = int(f,x,a,b)
g =
(

atan( (b-c1)/c2^(1/2) )*c4^(1/2)


+ atan( (b-c3)/c4^(1/2) )*c2^(1/2)
+ c5*b*c2^(1/2)*c4^(1/2)
)/c2^(1/2)/c4^(1/2)
- ( atan( (a-c1)/c2^(1/2) )*c4^(1/2)
+ atan( (a-c3)/c4^(1/2) )*c2^(1/2)
+ c5*a*c2^(1/2)*c4^(1/2) )/c2^(1/2)/c4^(1/2)

which can be rearranged as


g =

( atan((c1-a)/sqrt(c2)) - atan((c1-b)/sqrt(c2)) )/sqrt(c2) ...


+ ( atan((c3-a)/sqrt(c4)) - atan((c3-b)/sqrt(c4)) )/sqrt(c4) ...
+ c5*(b-a);

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Numerical Integration

11.8 F.M. White (Fluid Mechanics, fourth edition, 1999, McGraw-Hill, New York., problem 6.57)
gives the following data for the velocity prole in a round pipe
r/R
u/uc

0.0
1.0

0.102
0.997

0.206
0.988

0.412
0.959

0.617
0.908

0.784
0.847

0.846
0.818

0.907
0.771

0.963
0.690

r is the radial position, R = 12.35 cm is the radius of the pipe, u is the velocity at the position r,
and uc is the velocity at the centerline r = 0. The average velocity in a round pipe is dened by
V =

1
R2


0

u 2r dr,

or

V
=
uc

2
0

V
d,
uc

where = r/R. What is the value of V for the given data if uc = 30.5 m/s? Do not forget to include
the implied data point u/uc = 0 at r/R = 1. The data in the table is in the vprofile.dat le in
the data directory of the NMM toolbox.
Typographical Error: A factor of 2 is missing from the second integral expression. The correct
formula for V /uc is
 1
V
V
=
2 d
uc
u
c
0
Numerical Answer: Using trapzDat function with the correct form of the integral for V /uc ,
gives V = 25.4870 m/s.

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 11: Numerical Integration

11.12 Use the Trapezoid rule to evaluate



(m, n) =

xm1 (1 x)n1 dx

for any m and n and for a sequence of decreasing panel sizes h. Print the value of (m, n), and
the error relative to the value returned by the built-in beta function. Use your function to evaluate
(1, 2), (1.5, 2.5), (2, 3), and (2, 5). Comment on the convergence rate. (Hint: The values of m
and n can be passed around (not through) trapezoid with global variables.)
Partial Solution: The solution is obtained by writing two m-le functions. One function evaluates
the integrand, and the other calls trapezoid with a sequence of decreasing panel sizes. This second
m-le is obtained with minor modications to the demoTrap function. Ive called it betaTrap. The
prologue of the betaTrap function is
function betaTrap(m,n)
% betaTrap Evaluate beta function with trapezoid rule
%
% Synopsis: betaTrap
%
betaTrap(m,n)
%
% Input: m,n = (optional) parameters of the beta function
%
Default: m = 1, n = 2
%
% Output: Table of integral values as a function of decreasing panel size

Running betaTrap for m = 1 and n = 2 gives


>> betaTrap
Iexact =
n
3
5
9
17
33
65
129
257

h
0.50000
0.25000
0.12500
0.06250
0.03125
0.01562
0.00781
0.00391

0.500000000
I
0.500000000
0.500000000
0.500000000
0.500000000
0.500000000
0.500000000
0.500000000
0.500000000

error
0.000000000
0.000000000
0.000000000
0.000000000
0.000000000
0.000000000
0.000000000
0.000000000

alpha
-0.00000
-0.00000
-0.00000
-0.00000
-0.00000
-0.00000
-0.00000

The numerical integral is exact in this case becuase the integrand reduces to (1 x). The trapezoid
rule integrates a linear function with no truncation error.
Running betaTrap for m = 1.5 and n = 2.5 gives
>> betaTrap(1.5,2.5)
Iexact =

0.196349541

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Numerical Integration
n
3
5
9
17
33
65
129
257

h
0.50000
0.25000
0.12500
0.06250
0.03125
0.01562
0.00781
0.00391

I
0.125000000
0.170753175
0.187231817
0.193113697
0.195203315
0.195943901
0.196206057
0.196298800

error
-0.071349541
-0.025596365
-0.009117724
-0.003235844
-0.001146226
-0.000405639
-0.000143484
-0.000050741

alpha
1.47897
1.48919
1.49453
1.49725
1.49862
1.49931
1.49965

The theoretical value of = 2 is not obtained becuase the derivative of the integrand is not dened
at the lower limit of integration. The truncation error for the composite trapezoid rule is bounded
by Ch2 f  () where C is a constant and f  () is the second derivative of
the integrand evaluated at
some point in the limits of integration. For m = 1.5 and n = 2.5, f = x(1x)3/2 and f  (x)
as x approaches zero. Although the formulas in the trapezoid rule do not encounter a division by
zero, the truncation error reduces more slowly than O(h2 ) because of the contribution of f  ().

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 11: Numerical Integration

11.16 Evaluate


I=

x dx

using the NMM routines trapezoid, simpson, and gaussQuad. For each routine, evaluate the
integral for at least three dierent panel sizes. Present a table comparing the measured truncation
error as a function of panel size. Report any problems in obtaining values of I. Which routine works
best for this problem?
Partial Solution: The solution is obtained by modifying the code in the demoTrap, demoSimp,
and demoGauss functions. For convenience the modied code from these function is combined into
a single m-le called intSqrt. Running intSqrt gives:
>> intSqrt
Evaluate Integral with Trapezoid Rule:
n
3
5
9
17
33
65
129
257

h
0.50000
0.25000
0.12500
0.06250
0.03125
0.01562
0.00781
0.00391

I
0.603553391
0.643283046
0.658130222
0.663581197
0.665558936
0.666270811
0.666525657
0.666616549

error
-0.063113276
-0.023383620
-0.008536445
-0.003085470
-0.001107730
-0.000395855
-0.000141009
-0.000050118

Evaluate Integral with Simpsons Rule:


n
3
5
9
17
33
65
129
257

h
0.50000
0.25000
0.12500
0.06250
0.03125
0.01562
0.00781
0.00391

I
0.656526265
0.663079280
0.665398189
0.666218183
0.666508103
0.666610606
0.666646846
0.666659659

Iexact =

alpha
1.43245
1.45379
1.46815
1.47788
1.48456
1.48918
1.49240

Iexact =

error
-0.010140402
-0.003587387
-0.001268478
-0.000448484
-0.000158564
-0.000056061
-0.000019820
-0.000007008

Evaluate Integral with Gauss-Legendre Rule:

0.6666667

0.6666667
alpha
1.49911
1.49983
1.49997
1.49999
1.50000
1.50000
1.50000

Iexact =

0.6666667

Gauss-Legendre quadrature with 4 panels, H = 0.250000


nodes
1
2
3
4
5
6
7
8

I
0.6729773970
0.6675777702
0.6669809064
0.6668117912
0.6667454321
0.6667141381
0.6666974690
0.6666877808

error
6.31e-03
9.11e-04
3.14e-04
1.45e-04
7.88e-05
4.75e-05
3.08e-05
2.11e-05

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Numerical Integration

Gauss-Legendre quadrature with 8 nodes


panels
2
4
8
16
32
64
128
256

H
0.50000
0.25000
0.12500
0.06250
0.03125
0.01562
0.00781
0.00391

I
0.6667263866
0.6666877808
0.6666741317
0.6666693059
0.6666675998
0.6666669966
0.6666667833
0.6666667079

error
5.97e-05
2.11e-05
7.46e-06
2.64e-06
9.33e-07
3.30e-07
1.17e-07
4.12e-08

alpha
1.50
1.50
1.50
1.50
1.50
1.50
1.50

None of the integration rules achieves its theoretical truncation error. The reason is that the integrand is not suciently dierentiable at the lower limit of integration. (See also the solution to
Exercise 11-12.) The GaussLegendre rule with eight nodes per panel obtains the result with the
smallest error, though its performance is considerable worse on this integrand than on the integrands
demonstrated in the Examples in the text.

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 11: Numerical Integration

 2
11.22 Write an m-le function that evaluates 0 sin2 (x) dx using the composite trapezoid rule,
composite Simpsons rule, and composite GaussLegendre quadrature with four nodes per panel.
Place the calls to trapezoid, simpson, and gaussQuad inside a loop and repeat the calculations
for np = [2 4 8 16 32 64], where np is the number of panels. Record the number of function
evaluations, n, for each method. Print the absolute error |I Iexact | for the three methods versus n.
(See, for example, [13, 2.9] for help in explaining the results.)
Partial Solution: The computations are carried out with the compint_sinx2 function. The
prologue for compint_sinx2 is
function compint_sinx2(a,b)
% compint_sinx2 Compare quadrature rules for integral of (sin(x))^2
%
% Synopsis: compint_sinx2
%
compint_sinx2(a,b)
%
% Input:
a,b = (optional) limits of integration. Default: a=0; b=pi
%
% Output:
Values of integral obtained by trapezoid and simpsons rules
%
for increasing number of panels

Running compint_sinx2 with the default inputs gives:


>> compint_sinx2
Integral of (sin(x))^2 from 0*pi to 1*pi
Iexact =
1.570796327

n
3
5
9
17
33
65

Trapezoid
error
0.00000e+00
0.00000e+00
0.00000e+00
0.00000e+00
0.00000e+00
0.00000e+00

n
5
9
17
33
65
129

Simpson
error
0.00000e+00
0.00000e+00
0.00000e+00
0.00000e+00
0.00000e+00
0.00000e+00

Gauss-Legendre
error
8
0.00000e+00
16
0.00000e+00
32
0.00000e+00
64
-2.22045e-16
128
0.00000e+00
256
0.00000e+00
n

Note that n is the number of nodes at which the integrand is evaluated, not the number of panels
used by the various composite rules. All methods give neglible errors regardless of the number of
panels. The trapezoid rule is known to rapidly converge for a periodic integrand when the limits
of the integral are points at which the integrand and its derivative assume periodic values. See
Davis and Rabinowitz [13, 2.9] for details. sin2 x is an extreme example of the special behavior for
periodic integrands.
A slightly more interesting results is obtained if np = [ 1 2 4 8 16 32] and the GaussLegendre
rule with two (instead of four) points per panel is used. Making these changes and running the
modied compint_sinx2 gives
>> compint_sinx2
Integral of (sin(x))^2 from 0*pi to 1*pi
Iexact =
1.570796327
c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

10

Numerical Integration

n
2
3
5
9
17
33

Trapezoid
error
-1.57080e+00
0.00000e+00
0.00000e+00
0.00000e+00
0.00000e+00
0.00000e+00

n
3
5
9
17
33
65

Simpson
error
5.23599e-01
0.00000e+00
0.00000e+00
0.00000e+00
0.00000e+00
0.00000e+00

Gauss-Legendre
error
2
-3.77963e-01
4
0.00000e+00
8
0.00000e+00
16
0.00000e+00
32
0.00000e+00
64
0.00000e+00

This result allows direct comparison with somewhat more comparable number of nodes in each row.
The rst row shows the error for applying the basic rule for each method.
If, for the integral in this Exercise, the limits of the integral are shifted to 0 and some nonrational multiple of , the integration schemes behave as usual. Rerunning the modied version
of compint_sinx2 gives
>> compint_sinx2(0,5.12*pi)
Integral of (sin(x))^2 from 0*pi to 5.12*pi
Iexact =
7.871340417

n
2
3
5
9
17
33

Trapezoid
error
-6.78146e+00
4.33692e-01
-3.98177e-01
3.33054e-01
6.19534e-02
1.46620e-02

n
3
5
9
17
33
65

Simpson
error
2.83874e+00
-6.75466e-01
5.76797e-01
-2.84133e-02
-1.10178e-03
-6.25700e-05

Gauss-Legendre
error
2
-7.23535e+00
4
2.67829e-01
8
-4.38233e-01
16
1.95645e-02
32
7.40447e-04
64
4.17971e-05

Now the truncation errors do not decrease so dramatically because the limits of the integral do not
produce periodic values of the integrand and its derivatives.

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Selected Solutions for Exercises in

Numerical Methods with Matlab:


Implementations and Applications
Gerald W. Recktenwald
Chapter 12
Numerical Integration of
Ordinary Dierential Equations

The following pages contain solutions to selected end-of-chapter Exercises


from the book Numerical Methods with Matlab: Implementations and
c 2001, Prentice-Hall, Upper
Applications, by Gerald W. Recktenwald, 
c 2001 Gerald W. Recktenwald. The
Saddle River, NJ. The solutions are 
PDF version of the solutions may be downloaded or stored or printed only
for noncommercial, educational use. Repackaging and sale of these solutions
in any form, without the written consent of the author, is prohibited.
The latest version of this PDF le, along with other supplemental material
for the book, can be found at www.prenhall.com/recktenwald.

ODE Integration

12.3 Manually perform three steps of Eulers method to solve


dy
1
=
,
dt
t+y+1

y(0) = 0,

with h = 0.2.
Partial Solution:
0.426493.

Eulers method predicts y(0.6) = 0.4576112.. The exact solution is y(0.6) =

12.7 (Stoer and Bulirsch [70]) Use Eulers method with h = 0.05 to solve
dy
= y,
dt

y(0) = 0,

0 t 2.

Plot a comparison of the numerical solution with the exact solution. Does the plot indicate that
there is an error in odeEuler? If there is no error in odeEuler, can you explain the peculiar results?
Recompute the solution with odeMidpt and odeRK4. (Hint: What happens if the initial condition
y(0) = m is used instead of y(0) = 0? )
Solution: The exact solution is y = (t/2)2 . Evaluating the numerical solution gives yj = 0 for any
h. This result is not due to an error in odeEuler. The behavior of Eulers method is the same as
the behavior of any one-step method for this ODE: all one-step numerical solutions are yj (tj ) = 0
regardless of step size.
The general one-step formula is (cf. Equation (12.23))
yj = yj1 + h(t, y, h, f )
For this ODE, (t, y, h, f ) = 0 at t = 0 for any h, so that y2 = 0 (the rst step) for any one-step
method. Furthermore, (t, y, h, f ) = 0 whenever y = 0 so the numerical solution will remain stuck
at yj = 0 for all j. The trick to solving this problem is to perturb the initial condition, for example,
by using y(0) = m instead of y(0) = 0. By intentially introducing this neglible error in the initial
condition, the numerical solution will produce (t, y, h, f ) = 0 for the rst and subsequent time
steps.
The odeEulerSqrt function performs two numerical integrations of the ODE using Eulers method.
One numerical solution is with y(0) = 0 and the other is with y(0) = m .
function demoEulerSqrt
% demoEulerSqrt Solve y = sqrt(y),
% reference:

y(0) = 0;

Exact solution:

y = (t/2)^2

Bulirsh and Stoer, Chapter 7, exericse 4

diffeq = inline(sqrt(y),t,y);
tn = 2; y0 = 0;
% --- Two solutions differing by the value of y(0)
[t1,y1] = odeEuler(diffeq,tn,tn/100,y0);
[t2,y2] = odeEuler(diffeq,tn,tn/100,y0+eps);
% --- Evaluate exact solution and plot comparison
ye = (t2/2).^2;
plot(t2,ye,-,t1,y1,o,t2,y2,s);
legend(Exact,y(0)=0,y(0)=\epsilon_m,2);
title(Solutions by odeEuler);
xlabel(t);
ylabel(y);
c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 12: ODE Integration

Running odeEulerSqrt produces the plot on the next page.


Solutions by odeEuler
1
Exact
y(0)=0
y(0)=m

0.9

0.8

0.7

0.6

0.5

0.4

0.3

Plot of solution to
Exercise 127.

0.2

0.1

0.2

0.4

0.6

0.8

1
t

1.2

1.4

1.6

1.8

12.10 Using odeEuler.m as a guide, write an m-le to implement Heuns method for an arbitrary,
rst-order ODE. Use your function to solve equation (12.11) for h = 0.2, h = 0.1, h = 0.05, and
h = 0.025. Compare the global discretization error of your program with the theoretical prediction
of the global discretization error for Heuns method.
Partial Solution: The odeHeun function is obtained by making small modications to either
the odeEuler or odeMidpt function. Once odeHeun is written, it can be called (for example) by
demoHeun which is a trivial modication of the demoEuler function. The partial output of running
demoHeun for h = 0.1, h = 0.05, and h = 0.025 is
Max error =
Max error =
Max error =

3.58e-03 for h = 0.100000


8.27e-04 for h = 0.050000
1.99e-04 for h = 0.025000

12.12 For each of the following initial value problems, verify that the given y(t) is the solution.
(a)

t2
dy
=
y;
dt

y(0) = 1;

y(t) =


12
t 2t + 2 + ( 2)et

Solution (a): The easiest way to verify that the proposed solution is correct is by direct substitution into the initial value problem. The proposed solution is correct only if it satises the ODE
and the initial condition.
Begin by evaluating d/dt of the proposed analytical solution.




d 12
1
t 2t + 2 + ( 2)et =
2t 2 ( 2)et
dt

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

( )

ODE Integration

Next, substitute the proposed analytical solution into the right hand side of the ODE


t2
12
1
t2
y =

t 2t + 2 + ( 2)et =
2t 2 ( 2)et

( )

Comparing the far right hand side of Equation ( ) with the far right hand side of Equation ( ) we
see that the proposed solution satises the ODE.
Now, verify the initial condition.
y(0) =

1
1 2
0 (2)(0) + 2 + ( 2)e0 = [0 0 + 2 + 2] = = 1

Therefore, since the proposed solution satises both the dierential equation an the initial condition,
it is a solution to the initial value problem. Since the initial value problem is linear, the solution is
unique.

12.15 Repeat Exercise 13 using the built-in ode23 method and ode45 methods to solve the equations. Do not attempt to run the sequence of decreasing h values. (Why not?) Instead, compare
the solutions from ode23 and ode45 using the default convergence parameters.
Solution (a):

Use ode23 and ode45 to solve


t2
dy
=
y;
dt

y(0) = 1;

with = 3, y0 = 1, tn = 2. The exact solution is


y(t) =


12
t 2t + 2 + et
3

The demoOde2345_1a uses ode23 and ode45 to obtain the numerical solutions.
function demoOde2345_1a
% demoOde2345_1a Integrate dy/dt = (t^2)/3 - y with ode23 and ode45
%
% Synopsis:
demoOde2345_1a
%
% Input:
none
%
% Output:
A table comparing the numerical and exact solutions
rhs = inline((t.^2)/3 - y,t,y);
exact = inline((t.^2 - 2*t +2 + exp(-t))/3,t);

%
%

rhs of ODE
exact solution

tn = 2; y0 = 1;
% stopping time and IC
[t23,y23] = ode23(rhs,tn,1);
% solution with ode23
[t45,y45] = ode45(rhs,tn,1);
% solution with ode45
yex = exact(t45);
% Exact solution
plot(t23,y23,o,t45,y45,s,t45,yex,-);
fprintf(\nMax error = %10.2e for ode23\n,norm(y23-exact(t23),inf));
fprintf(Max error = %10.2e for ode45\n,norm(y45-yex,inf));
legend(ode23,ode45,exact);

Running odeEulerSqrt produces


c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 12: ODE Integration

>> demoOde2345_1a
Max error =
Max error =

2.41e-04 for ode23


1.97e-07 for ode45

and the plot on the next page. The plot of the solutions by ode23 and ode45 appear to be in good
agreement with the exact solution. A quantitative comparision of the methods shows that ode45
produces a more accurate result. The maximum error (which is the same as the global discretization
error) produced by ode45 is much smaller than the maximum error produced by ode23.
1
ode23
ode45
exact
0.9

0.8

0.7

0.6

Plot of solution to
Exercise 1215.

0.5

0.4

0.2

0.4

0.6

0.8

1.2

1.4

1.6

1.8

12.25 Create modied version of the rhsSmd function (see Listing 12.13 on page 723) to implement
the following forcing functions for the second order springmassdamper system of Example 12.12.
ramp

negative step
F0

F0
t

t
2

(a) Sinusoidal force input. F (t) = F0 sin(t), where = n .


(b) Ramp force input from 0 to 2 seconds, then constant at F0 .
(c) Constant force of F0 for a duration of 1 second, then zero force.
Compare the system responses for F0 = 1. Hint: Write a separate m-le function to evaluate
each F (t) for parts (a), (b), and (c). A particular F (t) function is then chosen at run-time, not
by repeated editing of rhsSmd. One way to do this is to pass the name of the chosen F (t) m-le
through ode45 to the modied rhsSmd function, where the F (t) function is then called with the
built-in feval function. In this implementation, the name of the F (t) function should also be an
input to the modied demoSmd function.
c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

ODE Integration

Partial Solution: The modied rhsSmd function is called rhsSmdVarInput. The compatible mle to evaluate step input forcing function is called stepFun. Both m-les are listed on the following
page
function dydt = rhsSmdVarInput(t,y,flag,zeta,omegan,inFun,u0,tin)
% rhsSmdVarInput RHS of coupled ODEs for a spring-mass-damper system
%
Variable forcing functions are specified on input
%
% Synopsis: dydt = rhsSmdVarInput(t,x,flag,zeta,omegan,a0)
%
% Input: t
= time, the independent variable
%
y
= vector (length 2) of dependent variables
%
y(1) = displacement and y(2) = velocity
%
flag
= dummy argument for compatibility with ode45
%
zeta
= damping ratio (dimensionless)
%
omegan = natural frequency (rad/s)
%
inFun = (string) name of m-file to evaluate forcing function
%
Currently allowed functions are stepFun, rampFun
%
stepDownFun, and sineFun
%
u0
= magnitude of force input function
%
tin
= time scale for force input. Meaning of tin
%
depends on value of inFun:
%
%
inFun
meaning of tin
%
-------------------------------%
stepFun
Time at start of step (tin = 0, usually)
%
rampFun
Time at end of ramp, input is constant for t>tin
%
stepDownFun Time at which input is set to zero.
%
For 0 <= t <= tin, input is u0
%
sineFun
Time units *per radian* of oscillatory input.
%
f = u0*sin(t/tin)
%
% Output:
dydt = column vector of dy(i)/dt values
f = feval(inFun,t,u0,tin);
dydt = [ y(2); f - 2*zeta*omegan*y(2) - omegan*omegan*y(1)];

function f = stepFun(t,u0,tin)
% stepFun Step input in force
if t<=tin,
else,
end

f = 0.0;
f = u0;

%
%

zero input before the step


step input

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

Chapter 12: ODE Integration

12.27 Dungs equation


d2 x
+ kx + x3 = B cos t
dt2
describes the chaotic dynamics of a circuit with a nonlinear inductor. (See, for example, Moon [57]).
Convert this equation to a system of two rst-order ODEs, and solve the system for k = 0.1 and
B = 12 and 0 t 100. Create the Poincare map of the system by plotting y2 versus y1 .
Typographical Error: In the rst printing of the book, the problem statement incorrectly asserts
that the Poincare map is obtained by plotting dx/dt versus t. Instead, the Poincare map is a plot
of the state variables against each other with time as the parameter. For this problem the map is
obtained by plotting dx/dt versus x.
Partial Solution:

The Poincare map is shown below


Two Equation Duffing model

y2

-2

-4

Plot of solution to
Exercise 1227.

-6

-8
-4

-3

-2

-1

0
y

c 2001, Gerald W. Recktenwald. Photocopying is permitted only for non-commercial educational purposes.
Copyright 

You might also like