Matlab please 17-UDF-4 Spring 2017 wrk Due: 4/11/2017 Submit your work to the Dr
ID: 2081886 • Letter: M
Question
Matlab please 17-UDF-4 Spring 2017 wrk Due: 4/11/2017 Submit your work to the Dropbox in a file named Bisection.m The "root" of an equation, ysf(x), is a value of x for which y has a value of zero and it is often "the answer for a practical engineering problem. The Bisection method is one of the simplest and most robust numerical methods for computing an approximate value for a root of a function. An explanation of the Bisection method is presented on the following page. Craft a UDF that performs the following tasks. 1. Accepts as an input argument a 4-element vector containing: the lower bound for the search interval the upper bound for the search interval a value of f(x close enough to zero to acceptxas an approximate value for a root the maximum number of iterations before termination of execution. 2. Calls another UDF, myFunction, saved in a different m-file, to compute values of the independent variable from values of the dependent variable. No credit will be earned for this assignment if you do not use the specified function name. 3. Reports to the CW one of the two possible outcomes. a) a root is found, the approximate value of the root and the corresponding value of the lfa function, b) That an approximate value for a root has not been found after iterations where the hyphens are the number of iterations conducted. The file you submit to the dropbox should have only the UDF that performs the bisection. [10] HINT: You may wish to use a while-construct to terminate execution. NOTE: Although this method is considered slow compared to other numerical methods for finding the root of a function, after only20 iterations the length of the search interval will be less than 1 millionth of its starting length!Explanation / Answer
%CALLING CODE
clc;
close all;
clear all;
tol = 1.0E-5;
x = [-1 3];
root = myfun(x,tol)
%myfun.m
function fn = myfun( x,tol)
fun = @(x) x.^3 -2*x -10;
fn = mybisect(fun,x,2,tol);
return;
end
%mybisect.m
function r = mybisect(fun,xb,xtol,ftol )
a = xb(1); b = xb(2);
fa = feval(fun,a); fb = feval(fun,b);
if sign(fa)==sign(fb)
error(sprintf('Root not bracketed by [%f %f]',a,b));
end
k = 0; maxit = 100;
while k<maxit
k=k+1
dx=b-a;
xm=a+0.5*dx;
fm=feval(fun,xm);
if(abs(fm)<ftol)|(abs(dx)<xtol)
r=xm;
return
end
if sign(fm)==sign(fa)
a=xm;fa=fm;
else
b=xm;fb=fm;
end
if k<3
sprintf('%d %2.2f %2.2f %2.2f %2.2f %2.2f %2.2f',k,xm,fm,a,fa,b,fb)
end
end
warning(sprintf('root not within tolerance after %d iteratins ',k));