numerical methods with matlab_recktenwald.pdf

Upload: mustafa-yilmaz

Post on 14-Jan-2016

127 views

Category:

Documents


33 download

TRANSCRIPT

  • 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 Exercisesfrom the book Numerical Methods with Matlab: Implementations andApplications, by Gerald W. Recktenwald, c 2000, Prentice-Hall, UpperSaddle River, NJ. The solutions are c 2000 Gerald W. Recktenwald. ThePDF version of the solutions may be downloaded or stored or printed onlyfor noncommercial, educational use. Repackaging and sale of these solutionsin any form, without the written consent of the author, is prohibited.

    The latest version of this PDF le, along with other supplemental materialfor the book, can be found at www.prenhall.com/recktenwald.

  • 2 Interactive Computing with Matlab

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

    A =

    1 5 23 4 97 2 6

    ; B =

    sin(1) sin(5) sin(2)sin(3) sin(4) sin(9)sin(7) sin(2) sin(6)

    Solution: Given a vector as input, the max function returns the maximum element. Givena matrix as input, the max function returns a row vector containing the maximum element ineach 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.9093

    0.1411 -0.7568 -0.4121

    -0.6570 0.9093 -0.2794

    >> max(max(B))

    ans =

    0.9589

    25 Use the linspace function to create vectors identical to those obtained with the statementsthat follow. Use multiple statements where necessary. (Use Matlabs built-in norm functionto 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 no-tation expressions in the rst column. To test whether these statements are correct, enter thecommands to create x and y, and then compute norm(x-y).

    colon notation linspacex = 0:10 y = linspace(0,10,11)x = -12:12 y = linspace(-12,12,25)

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

  • Chapter 2: Interactive Computing with Matlab 3

    29 Given the row vector x =[10 9 8 7

    ]and column vector

    y =

    1234

    write at least two dierent ways to compute the row vector z dened by zi = xi yi. Youranswers should take only one assignment operation. Do not, for example, explicitly write outequations 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

    E =

    0 0 10 1 01 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 dashedline and label the points with open circles. (Hint : Users of Matlab version 4 will need toplot the data twice in order to combine the symbol and line plots.)

    Partial Solution: The correct Matlab statements produce the following plot

    0 1 2 3 4 5 6 7-1

    -0.8

    -0.6

    -0.4

    -0.2

    0

    0.2

    0.4

    0.6

    0.8

    1

    sin(

    )

    Plot of solution toExercise 224.

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

  • 4 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 thesame plot. Label the axes and identify the curves with a legend.

    Partial Solution: The correct Matlab statements produce the following plot

    0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 0.16 0.18 0.20

    0.5

    1

    1.5

    2

    2.5

    Time (arbitrary units)

    Dis

    plac

    emen

    t (ar

    bitrar

    y unit

    s)

    zeta = 0.10zeta = 0.30zeta = 0.90

    Plot of solution toExercise 225.

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

  • Chapter 2: Interactive Computing with Matlab 5

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

    xm 0.010 0.223 0.507 0.740 1.010 1.220 1.530 1.742 2.100ym 0.102 0.620 0.582 0.409 0.312 0.187 0.122 0.081 0.009y 0.0053 0.0490 0.0671 0.0080 0.0383 0.0067 0.0417 0.0687 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.5 0 0.5 1 1.5 2 2.5-0.1

    0

    0.1

    0.2

    0.3

    0.4

    0.5

    0.6

    0.7

    Plot of solution toExercise 230.

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

  • 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 Exercisesfrom the book Numerical Methods with Matlab: Implementations andApplications, by Gerald W. Recktenwald, c 2003, Prentice-Hall, UpperSaddle River, NJ. The solutions are c 2003 Gerald W. Recktenwald. ThePDF version of the solutions may be downloaded or stored or printed onlyfor noncommercial, educational use. Repackaging and sale of these solutionsin any form, without the written consent of the author, is prohibited.

    The latest version of this PDF le, along with other supplemental materialfor the book, can be found at www.prenhall.com/recktenwald.

  • 2 Matlab Programming

    3.3 Transform the takeout script in Listing 3.2 to a function. Add a single input argument calledkind that allows you to select a type of food from your list of favorite take-out restaurants. Insidethe body of the function, set up a multiple-choice if ... elseif ... end block to match thekind string with the predened restaurant types. Make sure that there is a default choiceeither arestaurant 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 dispfunctions have been used to display the restaurant name and number to the screen. This is betterat conveying the intent of the program, which is to print the name and telephone number. A readerof the original takeout function might conclude that the purpose of the function is to assign valuesthat 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 adefault restaurant instead of an error message. While you are at it, you might as well replace thectitious 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

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

  • Chapter 3: Matlab Programming 3

    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

  • 4 Matlab Programming

    3.7 Elvis Presley was born January 8, 1935, and died on August 16, 1977. Write an elvisAgefunction that returns Elviss age in years, assuming that he were alive today. (The fragment of codeon 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

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

  • Chapter 3: Matlab Programming 5

    3.10 Write a function called mydiag that mimics the behavior of the built-in diag function. At aminimum, the mydiag function should return a diagonal matrix if the input is a vector, and returnthe 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 tonish myDiag and verify that it works. Use the demoMyDiag function, listed on the next page, andany 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 % input is a vector

    r = max(m,n); % m=1 or n=1, pick largest to dimension D

    D = zeros(r,r);

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

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

  • 6 Matlab Programming

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

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

  • Chapter 3: Matlab Programming 7

    3.16 Write the Matlab statements that use a loop and the fprintf function to produce thefollowing table (the format of the numerical values should agree exactly with those printed in thetable).

    theta sin(theta) cos(theta)

    0 0.0000 1.0000

    60 0.8660 0.5000

    120 0.8660 -0.5000

    180 -0.0000 -1.0000

    240 -0.8660 -0.5000

    300 -0.8660 0.5000

    360 0.0000 1.0000

    Partial Solution: The body of the loop can be one line:

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

    Many other loop blocks can be made to work.

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

  • 8 Matlab Programming

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

    y = wx2

    24EI(6L2 4Lx+ x2) and = 1

    6wL3

    EI,

    where w is the load per unit length, E is Youngs modulus for the beam, I is the moment of inertiaof 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 displace-ment 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 thevalue 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));

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

  • Chapter 3: Matlab Programming 9

    3.28 The corvRain.dat le in the data directory of the NMM toolbox contains monthly precipi-tation data for Corvallis, Oregon, from 1890 to 1994. The data are organized into columns, wherethe rst column lists the year and the next 12 columns give the precipitation, in hundredths of aninch for each month. Write a Matlab function to compute and plot the yearly total precipitationin 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 theutils directory of the NMM toolbox will be helpful in reading the data without having to deletethe 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 adata le (corvRain.dat in this case) as input, and computes the precipitation totals. Your job isto 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 theoutput is not important. The numerical values will be helpful, however, as a check on your completeprogram.

    >> 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. Inother 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 twoparameter form of the max function to test maxi for a variety of vector inputs.

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

  • 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

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

  • 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 Nusseltnumber is correlated with the Reynolds number Re and Prandtl number Pr by

    Nu = CRemPr1/3, where Re =V d

    and Pr =

    cpk

    ,

    in which , , and cp are, respectively, the density, dynamic viscosity, and specic heat of the uidand V is the velocity of the uid approaching the cylinder. The parameters C and m depend on Reaccording to the following table:

    Re range c m0.4 4 0.989 0.3304 40 0.911 0.385

    40 4000 0.683 0.4664000 40,000 0.193 0.618

    40,000 400,000 0.027 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 atmosphereand 20C.

    = 1.204 kg/m3, = 1.82 105N s/m2, cp = 1007 J/(kg K), k = 26.3 103W/(m C)

    Typographical Error: In the rst printing of the text, the value of k is given as 26.3W/(m C),which is o by a factor of 1000. The correct value of the thermal conductivity is k = 26.3 103W/(m C).

    Partial Solution: The values of c and m are set with an extended if...else construct. Thebeginning 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 thefollowing output.

    >> demoCylhtc

    diameter velocity Re h

    m m/s W/(m^2 C)

    0.001 0.008 0.53 18.693

    0.010 0.008 5.29 4.035

    0.200 0.015 198.46 0.937

    0.200 1.500 19846.15 10.190

    0.200 15.000 198461.54 57.894

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

  • Selected Solutions for Exercises in

    Numerical Methods with Matlab:Implementations and Applications

    Gerald W. Recktenwald

    Chapter 4

    Organizing and DebuggingMatlab Programs

    The following pages contain solutions to selected end-of-chapter Exercisesfrom the book Numerical Methods with Matlab: Implementations andApplications, by Gerald W. Recktenwald, c 2000, Prentice-Hall, UpperSaddle River, NJ. The solutions are c 2000 Gerald W. Recktenwald. ThePDF version of the solutions may be downloaded or stored or printed onlyfor noncommercial, educational use. Repackaging and sale of these solutionsin any form, without the written consent of the author, is prohibited.

    The latest version of this PDF le, along with other supplemental materialfor the book, can be found at www.prenhall.com/recktenwald.

  • 2 Organizing and Debugging

    4.2 Use stepwise renement to describe all of the steps necessary to compute the average andstandard deviation of the elements in a vector x. Implement these tasks in an m-le, and test yoursolution. Do not use the built-in mean and std functions. Rather, develop your solution from theequations 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 andvariance 2 are

    x =1n

    ni=1

    xi 2 =

    1n 1

    ni=1

    (xi x)2

    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. Data set of arbitray length with all xi = K, where K is a constant. Then x = K and = 0.

    Implementation of the code for computing x and is complicated in the case where n is large. Forlarge 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.

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

  • 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 Exercisesfrom the book Numerical Methods with Matlab: Implementations andApplications, by Gerald W. Recktenwald, c 2000, Prentice-Hall, UpperSaddle River, NJ. The solutions are c 2000 Gerald W. Recktenwald. ThePDF version of the solutions may be downloaded or stored or printed onlyfor noncommercial, educational use. Repackaging and sale of these solutionsin any form, without the written consent of the author, is prohibited.

    The latest version of this PDF le, along with other supplemental materialfor the book, can be found at www.prenhall.com/recktenwald.

  • 2 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. Converting0.4 to a binary number using Algorithm 5.1 gives (0 1100 1100 1100 . . .)2. To eight bits we get0.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

    =14+

    18+

    164

    +1128

    = 0.398437500

    59 Modify the epprox function in Listing 5.2 on page 207 so that vectors of n and abs(f-e) aresaved inside the loop. (Hint : Create the nn and err vectors, but do not modify the loop indexn.) Remove (i.e., comment out) the fprintf statements, and increase the resolution of theloop by changing the for statement to for n=logspace(1,16,400). Plot the variation of theabsolute 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 modica-tions. Running epproxPlot produces the plot on the following page. Explanation of the plotis 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));

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

  • Chapter 5: Unavoidable Errors in Computing 3

    100 102 104 106 108 1010 1012 1014 101610-10

    10-8

    10-6

    10-4

    10-2

    100

    102

    n

    Abso

    lute

    erro

    r in

    f(n)

    Plot of solution toExercise 59.

    519 Implement the combined tolerance |xk xk1| < max [a, r|xk1|] in the newtsqrt functionin Listing 5.3. Note that a and r should be separate inputs to your newtsqrt function. As adiagnostic, print the number of iterations necessary to achieve convergence for each argumentof 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 andtestConvSqrt functions listed below. The newtsqrt function is a modied version of thenewtsqrtBlank.m le in the errors directory of the NMM Toolbox. The modied le is savedas newtsqrt.m. The testConvSqrt function is a modied version of testsqrt function inListing 5.4.

    The inputs to newtsqrt are x, the argument of the square root function (newtsqrt returnsan 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 inputtolerances, whereas the newtsqrt function in Listing 5.3 has only one tolerance (delta). Thedefault tolerances in testConvSqrt are

    deltaA = 5m = 1.11 1015

    deltaR = 5 106

    The absolute tolerance is designed prevent unnecessary iterations: values of rrold less thanm are meaningless due to roundo. The relative tolerance corresponds to a change in theestimate of the root of less than 0.05 percent (0.0005) on subsequent iterations.

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

  • 4 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

  • Chapter 5: Unavoidable Errors in Computing 5

    523 Use the sinser function in Listing 5.5 to evaluate sin(x), for x = /6, 5/6, 11/6, and17/6. Use the periodicity of the sine function to modify the sinser function to avoid theundesirable behavior demonstrated by this sequence of arguments. (Hint : The modicationdoes 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 term ssum

    1 8.901e+00 8.90117919

    3 -1.175e+02 -108.64036196

    5 4.656e+02 357.00627682

    7 -8.784e+02 -521.41383256

    9 9.666e+02 445.22638523

    11 -6.963e+02 -251.02690828

    13 3.536e+02 102.59385039

    15 -1.334e+02 -30.82387869

    17 3.886e+01 8.03942600

    19 -9.003e+00 -0.96401885

    21 1.698e+00 0.73443795

    23 -2.659e-01 0.46848851

    25 3.512e-02 0.50360758

    27 -3.964e-03 0.49964387

    29 3.868e-04 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 convergingtoward the exact value of 0.5. Since the large terms alternate in sign, there is a loss of precisionin the least signicant digits when the large terms with opposite sign are added together toproduce a small result. Thus, even if more terms are included in the series, it is not possible toobtain 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 thesequence.

    The results of running sinser for x = /6, 5/6, 11/6, and 17/6 are summarized in thetable below.

    x Terms Absolute Error

    /6 6 3.56 10145/6 10 1.16 101111/6 15 4.40 101117/6 15 3.06 1005

    For smaller values of x, the series converges with fewer terms. The error in the approximationto sin(x) grows as |x| increases.

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

  • 6 Unavoidable Errors in Computing

    To reduce the eect of roundo for large x we exploit the periodicity of sin(x): the value ofsin(x) is the same for x 2n for n = 1, 2, . . .. Thus, whenever |x| > 2 we can remove aninteger factor of 2 before evaluating the series. Removing an integer factor of 2 is easilyachieved with the built-in rem function. rem(a,b) returns the remainder (fractional part) ofa/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 term ssum

    1 2.618e+00 2.61799388

    3 -2.991e+00 -0.37258065

    5 1.025e+00 0.65227309

    7 -1.672e-01 0.48502935

    9 1.592e-02 0.50094978

    11 -9.920e-04 0.49995780

    13 4.358e-05 0.50000139

    15 -1.422e-06 0.49999996

    17 3.584e-08 0.50000000

    19 -7.183e-10 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 eval-uating fewer terms.

    A even better solution involves recognizing that sin(x) for all x can be constructed from a tableof sin(x) values for 0 < x < /2. The diagram below indicates how values of sin(x) versus xcan be used to generate sin(x) values for any x.

    -8 -6 -4 -2 0 2 4 6 8-1.5

    -1

    -0.5

    0

    0.5

    1

    1.5

    Exercise 523. All values ofsin(x) can be generated fromsin(x) versus x in 0 x /2.

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

  • Chapter 5: Unavoidable Errors in Computing 7

    The following table gives additional clues on how to implement a more ecient and moreaccurate sinser

    Range of x Simplication

    2< x < sin(x) = sin( x)

    < x pi/2 & x> demoSinserMod2

    -- sinserMod -- -- sinserMod2 --

    x*6/pi n err n2 err2

    -17.00 10 1.156e-11 6 3.558e-14

    -11.00 15 -4.402e-11 6 -3.558e-14

    -5.00 10 1.156e-11 6 3.564e-14

    -1.00 6 3.564e-14 6 3.564e-14

    1.00 6 -3.564e-14 6 -3.564e-14

    5.00 10 -1.156e-11 6 -3.564e-14

    11.00 15 4.402e-11 6 3.558e-14

    17.00 10 -1.156e-11 6 -3.558e-14

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

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

  • 8 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)

    Pn(x) = f(x0) + (x x0) dfdx

    x=x0

    +(x x0)2

    2d2f

    dx2

    x=x0

    + + (x x0)n

    n!dnf

    dxn

    x=x0

    Given f(x) = 1/(1 x) we computedf

    dx=

    +1(1 x)2

    d2

    dx2=

    +2(1 x)3

    d3

    dx3=

    +6(1 x)4

    dn

    dxn=

    n!(1 x)n+1

    ThusP1(x) = f(x0) + (x x0) 1(1 x0)2

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

  • 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 Exercisesfrom the book Numerical Methods with Matlab: Implementations andApplications, by Gerald W. Recktenwald, c 2000, Prentice-Hall, UpperSaddle River, NJ. The solutions are c 2000 Gerald W. Recktenwald. ThePDF version of the solutions may be downloaded or stored or printed onlyfor noncommercial, educational use. Repackaging and sale of these solutionsin any form, without the written consent of the author, is prohibited.

    The latest version of this PDF le, along with other supplemental materialfor the book, can be found at www.prenhall.com/recktenwald.

  • 2 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. Giventhe 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 tobe 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-axistwice near x = 1.3. These two roots are missed by brackPlot because there default searchinterval is too coarse. There is no bug in brackPlot. Implementing a solution using a nersearch 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 anappropriate function m-le to evaluate the Colebrook equation.Partial Solution: Using bisect requires writing an auxiliary function to evaluate the Cole-brook equation in the form F (f) = 0, where f is the friction factor. The following form ofF (f) is used in the colebrkz function listed below.

    F (f) =1f+ 2 log10

    (/D

    3.7+

    2.51ReD

    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 passedthrough to the F (f) function, the values of /D and Re are passed to colebrkz via globalvariables. Running bisect with colebrkz is left to the reader. For Re = 1 105 and/D = 0.02 the solution is f = 0.0490.

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

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

    613 Derive the g3(x) functions in Example 6.4 and Example 6.5. (Hint : What is the xed-pointformula for Newtons method?)

    Partial Solution: The xed point iteration formulas designated as g3(x) in Example 6.4and Example 6.5 are obtained by applying Newtons method. The general form of Newtonsmethod for a scalar variable is

    xk+1 = xk f(xk)f (xk)

    Example 6.4: The f(x) function and its derivative are

    f(x) = x x1/3 2 f (x) = 1 13x2/3

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

    xk+1 = xk xk x1/3k 2

    1 (1/3)x2/3k=

    xk(1 (1/3)x2/3k ) (xk x1/3k 2)1 (1/3)x2/3k

    =xk (1/3)x1/3k xk + x1/3k + 2

    1 (1/3)x2/3k

    =(2/3)x1/3k + 2

    1 (1/3)x2/3k

    =2x1/3k + 6

    3 x2/3k

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

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

  • 4 Finding the Roots of f(x) = 0

    617 K. Wark and D. E. Richards (Thermodynamics, 6th ed., 1999, McGraw-Hill, Boston, Example14-2, pp. 768769) compute the equilibrium composition of a mixture of carbon monoxide andoxygen 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. Implementyour formula in a Matlab function and use your function to nd x. If your formula does notconverge, 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

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

    [3.06x(1 + x)1/2

    1 x]2 3

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

    1 x]2 3

    Another xed point iteration formula is obtained by solving for the isolated x in the denomi-nator to get

    x =(1 x)(3 + x)1/23.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 xnew

    1 -7.6420163e-01

    2 -2.5857113e+00

    3 -1.0721050e+01

    4 -7.9154865e+01

    5 -7.1666488e+02

    6 -6.6855377e+03

    7 -6.2575617e+04

    8 -5.8590795e+05

    9 -5.4861826e+06

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

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

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

    624 Create a modied newton function (say, newtonb) that takes a bracket interval as input insteadof a single initial guess. From the bracket limits take one bisection step to determine x0, theinitial guess for Newton iterations. Use the bracket limits to develop relative tolerances on xand 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 newnewtonb function.

    Running demoNewtonb gives

    >> demoNewtonb

    Original newton function:

    Newton iterations for fx3n.m

    k f(x) dfdx x(k+1)

    1 -4.422e-01 8.398e-01 3.52664429313903

    2 4.507e-03 8.561e-01 3.52138014739733

    3 3.771e-07 8.560e-01 3.52137970680457

    4 2.665e-15 8.560e-01 3.52137970680457

    5 0.000e+00 8.560e-01 3.52137970680457

    newtonb function:

    Newton iterations for fx3n.m

    k f(x) dfdx x(k+1)

    1 -4.422e-01 8.398e-01 3.52664429313903

    2 4.507e-03 8.561e-01 3.52138014739733

    3 3.771e-07 8.560e-01 3.52137970680457

    4 2.665e-15 8.560e-01 3.52137970680457

    5 0.000e+00 8.560e-01 3.52137970680457

    The two implementations of Newtons method give identical results because the input tonewtonb is the bracket [2, 4]. This causes the initial bisection step to produce the same initialguess 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);

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

  • 6 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

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

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

    xk+1 = xk f(xk)[

    (xk xk1)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) usingEquation (6.13). The f(x) function, Equation 6.3, is hard-coded into demoSecant. Note alsothat 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 initial guesses to local variables

    xk = b; % x(k)

    xkm1 = a; % x(k-1)

    fk = fx3(b); % f( x(k) )

    fkm1 = 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

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

  • 8 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 method: Algorithm 6.5, Equation (6.13)

    n x(k-1) x(k) f( x(k) )

    0 3.00000000 4.00000000 4.12599e-01

    1 4.00000000 3.51734262 -3.45547e-03

    2 3.51734262 3.52135125 -2.43598e-05

    3 3.52135125 3.52137971 1.56730e-09

    4 3.52137971 3.52137971 -8.88178e-16

    5 3.52137971 3.52137971 -2.22045e-16

    6 3.52137971 3.52137971 0.00000e+00

    7 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 beyondconvergence gives a oating point exception because f(xk) f(xk1) = 0 in the denominatorof Equation (6.13). In general, it is possible to have f(xk) f(xk1) = 0 before the secantiterations reach convergence. Thus, the oating point exception exposed by demoSecant shouldbe 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.

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

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

    633 Write an m-le function to compute h, the depth to which a sphere of radius r, and specicgravity s, oats. (See Example 6.12 on page 281.) The inputs are r and s, and the output ish. 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 errorfunction will be useful.) Your function needs to include logic to select the correct root fromthe list of values returned by the built-in roots function.

    Partial Solution: The floata function listed below performs the desired computations. Webriey discuss three of the key statements in floata The coecients of the polynomial arestored in the p vector. Then

    c = getreal(roots(p));

    nds the real roots of the polynomial. The getreal subfunction returns only the real elementsof a vector. Using getreal is a defensive programming strategy. The sample calculation inExample 6.12 obtained only real roots of the polynomial, so getreal would not be necessaryin that case. The

    k = find(c>0 & c

  • 10 Finding the Roots of f(x) = 0

    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(s0 & c1, 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

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

  • 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 Exercisesfrom the book Numerical Methods with Matlab: Implementations andApplications, by Gerald W. Recktenwald, c 2000, Prentice-Hall, UpperSaddle River, NJ. The solutions are c 2000 Gerald W. Recktenwald. ThePDF version of the solutions may be downloaded or stored or printed onlyfor noncommercial, educational use. Repackaging and sale of these solutionsin any form, without the written consent of the author, is prohibited.

    The latest version of this PDF le, along with other supplemental materialfor the book, can be found at www.prenhall.com/recktenwald.

  • 2 A Review of Linear Algebra

    7.3 Manually compute C = AB for

    A =[1 12 3

    ]B =

    [3 12 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 rowsof A and columns of B gives

    AB =[1 12 3

    ] [3 12 1

    ]=[(1)(3) + (1)(2) (1)(1) + (1)(1)(2)(3) + (3)(2) (2)(1) + (3)(1)

    ]

    =[(3 2) (1 + 1)(6 6) (2 + 3)

    ]=[1 00 1

    ]

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

    Alternatively, we can use Algorithm 7.5 to produce the same result. When we manually applyAlgorithm 7.5 we merely proceed down the rows of the result matrix. To make the organization ofAlgorithm 7.5 obvious, we can separately compute each column of the result matrix. Though thishelps 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

    AB(:,1) =[1 12 3

    ] [32]=[(1)(3) + (1)(2)(2)(3) + (3)(2)

    ]=[3 26 6

    ]=[10

    ]

    The second column of AB is

    AB(:,2) =[1 12 3

    ] [3 12 1

    ]=[(1)(1) + (1)(1)(2)(1) + (3)(1)

    ]=[1 + 12 + 3

    ]=[01

    ]

    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 thediagonal elements of A.

    tr(A) =n

    i=1

    aii

    Write a one-lineMatlab expression to compute the trace of a matrix, A. Do not use any for...endloops in your expression.

    Solution: trA = sum(diag(A))

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

  • Chapter 7: A Review of Linear Algebra 3

    7.14 Write an m-le function (say, matVecCol) that evaluates a matrix-vector product (vector onthe right) using the column view, Algorithm 7.1, and only one for...end loop. This is achievedby replacing the inner loop of Algorithm 7.1 with a single line of Matlab code that uses colonnotation. Test your function by comparing the output with A*x for random, but compatible, A andx.

    Typographical Error: In Algorithm 7.1, the statement initialize b = zeros(n, 1) should beinitialize b = zeros(m, 1)

    Partial Solution: The matVecCol function is listed below. Note that the initialization state-ment 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(A,x)

    % matVecCol Matrix-vector product as a linear combination of columns of A

    %

    % Synopsis: y = matVecCol(A,x)

    %

    % Input: 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 and x is %d by %d\n,...

    size(A),size(x)));

    end

    y = zeros(m,1); % initialization required

    for j=1:n

    y = x(j)*A(:,j) + y;

    end

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

  • 4 A Review of Linear Algebra

    7.21 Write a rowScale function that uses a single for...end loop to perform the diagonal scalingof 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.) Thesingle loop is possible with judicious use of colon wild cards. Before performing any calculations testto 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); end

    % --- loop over rows of A

    for i=1:m

    B(i,:) = d(i)*A(i,:); % scalar times a row vector

    end

    7.25 (1) Dene a matrix with columns given by the vectors in equation (7.18). Use the rankfunction 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 befull rank.

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

  • 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 Exercisesfrom the book Numerical Methods with Matlab: Implementations andApplications, by Gerald W. Recktenwald, c 2000, Prentice-Hall, UpperSaddle River, NJ. The solutions are c 2000 Gerald W. Recktenwald. ThePDF version of the solutions may be downloaded or stored or printed onlyfor noncommercial, educational use. Repackaging and sale of these solutionsin any form, without the written consent of the author, is prohibited.

    The latest version of this PDF le, along with other supplemental materialfor the book, can be found at www.prenhall.com/recktenwald.

  • 2 Solving Systems of Equations

    8.6 Manually solve QRx = b for x where

    Q =

    1/2 0 1/2

    0 1 01/2 0 1/

    2

    R = 2

    1 1 10 1 10 0 1

    b =

    222

    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, manipulatethe given equation as products of matrices and vectors. From Exercise 8.3 we know that QTQ = 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 solveRx = z for z with backward substitution. Given the preceding manipulations we can obtain aneasy 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

    z = QT b =

    1/2 0 1/

    2

    0 1 01/2 0 1/2

    222

    4

    =

    2/2 + 0 + 4/

    2

    0 + 22 + 0

    2/2 + 0 + 4/2

    =

    6/2

    22

    2/2

    Next solve2

    1 1 10 1 10 0 1

    x1x2x3

    =

    6/2

    22

    2/2

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

    1 1 10 1 10 0 1

    x1x2x3

    = 1

    2

    6/2

    22

    2/2

    =

    6/222/2

    =

    321

    Work from x3 up to x1 (backward substitution):

    x3 = 1

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

    Therefore the solution is x = [1, 1, 1]T . The following Matlab statements double-check the manualsolution. First, dene the Q, R, and b vectors as given

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

  • Chapter 8: Solving Systems of Equations 3

    >> 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 QTQ = 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(:) % convert x to column vector

    x =

    1.0000

    1.0000

    1.0000

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

  • 4 Solving Systems of Equations

    We used to the most general form of the backward substitution steps, and did not exploit the factthat all of the upper triangular elements of R are equal to one. Conversion of x from a row vectorto a column vector with x = x(:) is necessary because the x was rst created as a row vector withthe statement x(3) = z(3)/R(3,3).

    8.12 Starting with the code in the GEshow function, develop a GErect function that performsGaussian Elimination only (no backward substitution) for rectangular (mn) matrices. The GErectfunction should return A, the triangularized coecient matrix, and b, the corresponding right handside vector. Use the GErect function to solve Exercise 11.

    Partial Solution: The prologue and partial code for the GErect function is shown below. Theonly substantial dierence between GEshow and GErect is that GErect does not perform backwardsubstitution.

    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

  • Chapter 8: Solving Systems of Equations 5

    8.16 Write an lsolve function to solve Ax = b when A is a lower triangular matrix. Test yourfunction by comparing the solutions it obtains with the solutions obtained with the left divisionoperator.

    Partial Solution: The lsolve function is listed below. The reader is left to complete the Exerciseby 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 matrixmatrixmultiplication (see Algorithm 7.5 on page 327) we see that the jth column of A1 is the vector xsuch that Ax = e(j), where e(j) is the jth 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 ata 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 countof 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 matricesof increasing size. Use A = rand(n,n) for n = 2, 4, 8, 16, 32, . . . , 128. Compare the op count ofinvByCol with those of the built-in inv command. Note that the order-of-magnitude estimatewill only hold as n becomes large. Users ofMatlab version 6 will not be able to use the flopsfunction to measure the ops performed by inv. In that case, use the estimate that matrixinversion 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 followingstatements do the job

    for j=1:n

    e = zeros(n,1); e(j) = 1;

    Ai(:,j) = A\e;

    end

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

  • 6 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 jth column of Ai. The eciency of the loop can be improved by preallocating memory forAi, and using a xed zero vector z = zeros(n,1) instead of creating a new vector on each passthrough the loop. These improvements, along with provisions for input and output and some basicerror 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); end

    Ai = zeros(n,n); % pre-allocate for speed

    z = zeros(n,1); % temporary vector

    for j=1:n

    e = z; e(j) = 1; % reset column of I

    Ai(:,j) = A\e; % 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 functionappears to be working. Note that the L1 norm is chosen for eciency. Both the L and L2 normswould give equivalent results. The L norm would take less ops than the L1 norm. Both L1and L norms are signicantly more ecient than the L2 norm. For a 5 5 matrix the eciencydierences are irrelevant, however.

    Solution (b): Each solution of Ax = e(j) takes O(n3/3) ops. There are n columns of A1 so theinvByCol function takes nO(n3/3) = O(n4/3) ops for an n n matrix A. This is an expensiveway to compute A1.

    Solution (c): The demoInvByCol function (listed below) measures the ops performed by theinvByCol function and the built-in inv function. These functions are applied to a sequence of

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

  • Chapter 8: Solving Systems of Equations 7

    random nn matrices is generated for n = [2 4 8 16 32 64 128]. The elements of matrix A areunimportant as long as A is nonsingular. It turns out that the matrices generated by the built-inrand 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, thedemoInvByCol 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 obtainthe least squares t (see Fitting Lines to Apparently Nonlinear Functions in Chapter 9) to

    f = c1nc2

    where f is a vector of measured op counts and n is the vector of matrix dimensions. The c2exponent should be 4 for the invByCol function because the op count grows as O(4). (See solutionto part (b), above.) For the built-in inv function the c2 exponent should be 3 because the invfunction 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 selectsthe third through last elements of the vector. This improves the estimate of c2 because the order ofmagnitude 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));

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

  • 8 Solving Systems of Equations

    function c = powfit(x,y)

    % expfit Least squares fit of data to y = c1*x^c2

    %

    % Synopsis: c = powfit(x,y)

    %

    % Input: x,y = vectors of independent and dependent variable values

    %

    % Output: c = vector of coefficients: y = c(1)*x^c(2)

    if length(y)~=length(x), error(Dimensions of x and y are not compatible); end

    ct = linefit(log(x(:)),log(y(:))); % Line fit to transformed data

    c = [exp(ct(2)) ct(1)]; % Extract parameters from transformation

    Running demoInvByCol produces the following output and the plot below.

    >> demoInvByCol

    Flop counts:

    n invByCol inv

    2 96 51

    4 768 242

    8 7040 1412

    16 76128 9598

    32 952768 70942

    64 13163520 545040

    128 194685952 4276376

    exponent O(3.8) O(2.9)

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

    100 101 102 103101

    102

    103

    104

    105

    106

    107

    108

    109

    Number of unknowns

    flops

    invByCol flopsfit inv flops fit

    Exercise 821. Flop countsfor invByCol and inv.

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

  • Chapter 8: Solving Systems of Equations 9

    Extra Credit: The most costly phase of invByCol is repeatedly solving Ax = e(j). Rewrite theinvByCol 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 ofyour new function with the original version of invByCol.

    The extra credit solution is implemented in the invByColLU and demoInvByColLU functions (neitherare listed here). Running demoInvByColLU gives

    >> demoInvByColLU

    Flop counts:

    n invByCol inv invByColLU

    2 100 51 35

    4 752 242 226

    8 7168 1444 1588

    16 77216 9594 11816

    32 950400 70836 90960

    64 13186432 545124 713376

    128 194873088 4275098 5649728

    exponent O(3.7) O(2.9) O(3.0)

    The invByColLU function obtains the exact ops exponent value of 3 that is predicted by the orderof magnitude work estimates. The built-in inv function uses the ideas embodied in invByColLU tocompute A(1).

    8.25 An alternative way to resolve the singularity in the 3 3 coecient matrix of Example 8.5 isto modify the elements of the matrix. Write a trivial equation involving vb, vc, and vd that has thesolution vd = 0. Use this equation to replace the equation for vd in the 33 system in Example 8.5.What is the value of Vout for R1 = R3 = R4 = R5 = 10 k, R2 = 20 k and Vin = 5V .

    Partial Solution: The trivial equation with the solution vd = 0 is (0)vb + (0)vc + (1)vd = 0, orvd = 0.

    8.33 Use the pumpCurve function developed in Exercise 32 to study the eect of perturbing theinput data. Specically, replace the second h value, h = 114.2, with h = 114, and re-evaluatethe coecients of the cubic interpolating polynomial. Let c be the coecients of the interpolatingpolynomial derived from the perturbed data, and let c be the coecients of the polynomial derivedfrom the original data. What is the relative dierence, (ci ci)/ci, in each of the polynomialcoecients? Evaluate and plot h(q) for the two cubic interpolating polynomials at 100 data pointsin the range min(q) q max(q). What is the maximum dierence in h for the interpolants derivedfrom the original and the perturbed data? Discuss the practical signicance of the eect perturbingthe 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). RunningpumpPerturb gives the following output and plot..

    >> pumpPerturb

    Coefficients of cubic interpolant in descending powers of q:

    i c(i) ct(i) percent diff

    1 -1.1870738e+10 -1.3978775e+10 17.8

    2 1.0361305e+07 1.5209790e+07 46.8

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

  • 10 Solving Systems of Equations

    3 -7.8023933e+03 -1.0627163e+04 36.2

    4 1.1568850e+02 1.1592460e+02 0.2

    Maximum difference of h values = 0.253 (m) occurs at q = 3.89e-04

    Condition numbers: kappa(A) = 2.7e+10; kappa(At) = 2.7e+10

    c(i) are the coecients of the cubic polynomial derived from the unperturbed data. ct(i) are thecoecients derived from the perturbed data. Although the coecients have very large dierences inmagnitude, the values of the interpolants have a maximum dierence of only 0.25 m in head. Theperturbation has no signicant eect on the condition number of the Vandermonde system.

    0 0.5 1 1.5x 10-3

    90

    95

    100

    105

    110

    115

    120

    Flow rate (m3/s)

    Hea

    d (m

    )

    Data Original interpolant Perturbed interpolant point of max difference

    Exercise 833. Interpolantsfrom original and perturbed hdata.

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

  • Selected Solutions for Exercises in

    Numerical Methods with Matlab:Implementations and Applications

    Gerald W. Recktenwald

    Chapter 9

    Least Squares Fittingof a Curve to Data

    The following pages contain solutions to selected end-of-chapter Exercisesfrom the book Numerical Methods with Matlab: Implementations andApplications, by Gerald W. Recktenwald, c 2001, Prentice-Hall, UpperSaddle River, NJ. The solutions are c 2001 Gerald W. Recktenwald. ThePDF version of the solutions may be downloaded or stored or printed onlyfor noncommercial, educational use. Repackaging and sale of these solutionsin any form, without the written consent of the author, is prohibited.

    The latest version of this PDF le, along with other supplemental materialfor the book, can be found at www.prenhall.com/recktenwald.

  • 2 Least Curve Fitting

    9.3 Lipson and Sheth (Statistical Design and Analysis of Engineering Experiments, 1973, McGraw-Hill, p. 385) give data on the wear of a particular journal bearing as a function of operatingtemperture. Their data are contained in the bearing.dat le in the data directory of the NMMToolbox. Use the linefit function to t bearing wear as a function of temperature. Plot a com-parison of the data and the curve t on the same axes. From this data what is the limit on bearingtemperature if the wear should not exceed 8mg/100hr of operation?

    Numerical Answer: A plot of the t is shown below. The temperature limit is 500 C (T =499.5206 C).

    200 300 400 500 600 7000

    2

    4

    6

    8

    10

    12

    T ( C)

    Wea

    r (m

    g/100

    hr)

    Plot of solution toExercise 93.

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

  • Chapter 9: Least Curve Fitting 3

    9.6 The xyline.dat le contains two columns of numbers (x and y) that are reasonably well-ttedby 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 normof 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 precedingstep; 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 allcombinations 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 onthe 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 theoryused to develop the c for the least squares t.

    Partial Solution: Carrying out the computations in steps (a)(d) gives the plots on the nextpage.

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

  • 4 Least Curve Fitting

    0 5 10 151

    0.5

    0

    0.5

    1

    1.5

    2

    2.5

    x

    y

    DataFit

    Exercise 96. Plot (a):Curve t.

    0.30.25

    0.20.15

    0.1

    11.5

    22.5

    30

    1

    2

    3

    4

    5

    6

    c1

    Residual as function of c1 and c2

    c2

    ||r||2

    Exercise 96. Plot (b):Surface plot of residuals.

    0.26 0.24 0.22 0.2 0.18 0.16 0.14 0.12

    1.4

    1.6

    1.8

    2

    2.2

    2.4

    2.6

    2.8

    c1

    c 2

    Residual as function of c1 and c2

    Exercise 96. Plot (c):Contour plot of residuals.

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

  • Chapter 9: Least Curve Fitting 5

    9.7 Least squares tting problems with only one undetermined coecient lead to particularly simplecomputational procedures. Derive the equations for nding the (scalar) c coecient of the followingequations 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 thatx and y are column vectors. Hint : Write the overdetermined system and then form the normalequation.

    Solution (a): For m data pairs the overdetermined system is

    x1x2...xm

    c =

    y1y2...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 x2 xm

    ]

    x1x2...xm

    c =

    [x1 x2 xm

    ]

    y1y2...ym

    x

    Tx c = xT y

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

    c =xT y

    xTx

    Translating the preceding expression to Matlab gives

    >> x = ... (x and y are column vectors)>> y = ...

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

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

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

  • 6 Least Curve Fitting

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

    x 2.2500 2.5417 2.8333 3.1250 3.4167 3.7083 4.0000

    y 2.8648 1.4936 1.0823 0.8842 0.7677 0.6910 0.6366

    x 0.7000 1.0714 1.4429 1.8143 2.1857 2.5571 2.9286 3.3000

    y -0.1714 -0.3673 -0.8243 -3.1096 3.7463 1.4610 1.0039 0.8080

    Typographical Error: The correct form of the transformed linear relationship is z = c1 + c2w.

    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(

    0

    )= c1 + c2

    T

    T0+ c3

    (T

    T0

    )2

    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 theNMM Toolbox to nd values of the ci for water with T0 = 0 C. The rst column in H20Visc.datis the temperature in C, the second column is the viscosity in kg/(m s). Convert the temperatureto kelvins before performing the t.

    Numerical Answer: c1 = 15.5613, c2 = 23.4078, c3 = 7.8189

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

  • Chapter 9: Least Curve Fitting 7

    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 chemicalreaction 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 theuniversal gas constant, and T is the absolute temperature. Experimental data for a particularreaction yield the following results:

    T (K) 773.5 786 797.5 810 810 820 834

    k 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 Arrheniusequation can be written

    k = c1 exp(c2x) ()

    where c1 = A, c2 = Ea, and x = 1/(RT ). Therefore, by tting Equation () to the (k, T ) datawe obtain A and Ea. The curve t is easily performed with the expfit function developed as thesolution to Exercise 8.

    The curve t for the given data is computed in the demoArrhenius function listed below. Note thatthe fitArrhenius subfunction could be moved to a separate m-le so that it could be called byother m-les or invoked directly from the command window.

    Running demoArrhenius gives A = 1.87171013, Ea = 2.3803108, and the plot on the next page.

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

  • 8 Least Curve Fitting

    function demoArrhenius

    % demoArrhenius Demonstrate least squares fit to Arrhenius reaction rate equation

    % Uses the fitArrhenius function. Exercise 9-23

    % --- Store data

    r = 8314; % gas constant, J/(K*kg-mol)

    t = [773.5 786 797.5 810 810 820 834];

    k = [1.63 2.95 4.19 8.13 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

  • Chapter 9: Least Curve Fitting 9

    9.26 Write a function to t data to y = c1x5+c2x3+c3x+c4 without calling polyfit, fitnorm, orfitqr. Your function should take two column vectors, x and y, as input, and return the coecientvector. It should be self-contained, i.e, it should set up and solve the overdetermined system ofequations without calling any auxiliary functions. Test your solution with the following data.

    x -3.0000 -1.8571 -0.7143 0.4286 1.5714 2.7143 3.8571 5.0000y -4.9262 -4.4740 -3.3136 -2.9396 -2.6697 -1.3906 -0.8669 -3.3823

    Numerical Answer: c1 = 3.116759277 103, c2 = 6.286454564 102, c3 = 0.3375296900,c4 = 3.181091285.

    9.32 The pdxTemp.dat le in the data directory of the NMM toolbox contains historically averagedmonthly 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 arethe historically averaged low, high, and average temperature, respectively, for each month. Createa t of the average temperature to the function

    T = c1 + c2 sin2[(m 1)

    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 thebeginning 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 thet and the original data.

    0 2 4 6 8 10 12 1435

    40

    45

    50

    55

    60

    65

    70

    month

    Aver

    age

    tem

    pera

    ture

    (F)

    DataFit

    Plot of solution toExercise 932.

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

  • 10 Least Curve Fitting

    9.37 Lipson and Sheth (Statistical Design and Analysis of Engineering Experiments, 1973, McGraw-Hill, p. 385) give data on nitrogen oxide (NO) emission from an internal combusition engine as afunction of humidity and atmospheric pressure. Their data are contained in the emission.dat lein the data directory of the NMM toolbox. Obtain a multiple linear regression of this data of theform

    NO = c1 + c2h+ c3p

    where h is the humidity in grains per pound of dry air, and p is the atmospheric pressure in inchesof Mercury. What are the values of c1, c2 and c3?

    Numerical Answer: c1 = 5028.913856, c2 = 5.347260274, c3 = 117.4130076.

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

  • 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 Exercisesfrom the book Numerical Methods with Matlab: Implementations andApplications, by Gerald W. Recktenwald, c 2001, Prentice-Hall, UpperSaddle River, NJ. The solutions are c 2001 Gerald W. Recktenwald. ThePDF version of the solutions may be downloaded or stored or printed onlyfor noncommercial, educational use. Repackaging and sale of these solutionsin any form, without the written consent of the author, is prohibited.

    The latest version of this PDF le, along with other supplemental materialfor the book, can be found at www.prenhall.com/recktenwald.

  • 2 Interpolation

    10.3 What are the condition numbers for the two Vandermonde matrices in Examples 10.4 and10.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 andprinted to ve signicant digits. Evaluate the gasoline prices and the errors in the interpolant usingthe truncated coecients and the following denitions: Let (yi, pi) be the year and price in thegiven tabulated data. Let pi be the price interpolated with the untruncated polynomial coecientsat the yi, and pi be the price interpolated with the truncated coecients at the yi. In the absenceof numerical errors we expect pi = pi = pi from the denition of interpolation. Compute and printpi, pi pi, p p2, pi, p