Page 84 - Numerical Analysis Using MATLAB and Excel
P. 84

Solutions to End-of-Chapter Exercises




               2.
                   a. We will use the for end loop MATLAB program and specify 12 iterations. Before we write
                      the program script, we must define a function assigned to the given polynomial and save it
                      as a function m−file. We will define this function as exercise2 and will save it as

                      exercise2.m

                      function y= exercise2(x);
                      y = x .^ 4 +x − 3;
                      After saving this file as exercise2.m, we execute the following program:


                      x1=1;  x2=2;               % x1=a and x2=b
                      disp('   xm             fm')  % xm is the average of x1 and x2, fm is f(xm)
                      disp('-------------------------')  % insert line under xm and fm
                      for k=1:12;
                            f1=exercise2(x1); f2=exercise2(x2);
                      xm=(x1+x2) / 2; fm=exercise2(xm);
                      fprintf('%9.6f %13.6f \n', xm,fm)% Prints xm and fm on same line;
                      if (f1*fm<0)
                         x2=xm;
                       else
                         x1=xm;
                        end
                      end
                      MATLAB displays the following:


                         xm             fm
                      -------------------------
                      1.500000      3.562500
                      1.250000      0.691406
                      1.125000     -0.273193
                      1.187500      0.176041
                      1.156250     -0.056411
                      1.171875      0.057803
                      1.164063      0.000200
                      1.160156     -0.028229
                      1.162109     -0.014045
                      1.163086     -0.006930
                      1.163574     -0.003367
                      1.163818     -0.001584
                  b. We will use the while end loop MATLAB program and specify a tolerance of 0.00001.

                      We need to redefine the function m−file because the function in part (b) is not the same as
                      in part a.



               Numerical Analysis Using MATLAB® and Excel®, Third Edition                              2−31
               Copyright © Orchard Publications
   79   80   81   82   83   84   85   86   87   88   89