function XbbrackPlotfunxminxmaxnx brackPlot Find subinterva

function Xb=brackPlot(fun,xmin,xmax,nx)
% brackPlot: Find subintervals on x that contain sign changes of f(x)
% Synposis: Xb=brackPlot(fun,xmin,xmax)
% Xb=brackPlot(fun,xmin,xmax,nx)
% Input: fun=(string) name of mfile function that evaluates f(x)
% xmin,xmax=endpoints of interval to subdivide into brackets
% nx=(optional) number of samples along x axis used to test for
% brackets. The interval xmin<=x<=xmax is divided into nx-1
% subintervals. Default: nx=20
% Output: Xb=two column matrix of bracket limits. Xb(k,1) is the left
% (lower x value) bracket and Xb(k,2) is the right bracket for the
% k^th potential root. If no brackets are found, Xb=[].

if nargin<4
nx=20;
end

xp=linspace(xmin,xmax);
yp=feval(fun,xp);
plot(xp,yp,[floor(xmin) ceil(xmax)],[0 0]);
grid on;
xlabel(\'x\');
ylabel([\'f(x) defined in \',fun, \'.m\']);

ytop=max(yp);
ybot=min(yp);
ybox=0.05*[ybot ytop ytop ybot ybot];
c=[0.7 0.7 0.7];

x=linspace(xmin,xmax,nx);
f=feval(fun,x);
nb=0;
Xb=[];
for k=1:length(f)-1
if sign(f(k))~=sign(f(k+1))
nb=nb+1;
Xb(nb,1)=x(k);
Xb(nb,2)=x(k+1);
hold on;
fill([x(k) x(k) x(k+1) x(k+1) x(k)],ybox,c);
end
end
hold off
if isempty(Xb)
warning(\'No brackets found. Check [xmin,xmax] or increase nx\');
end

The function f(x) = sin(x^2) + x^2 - 2x - 0.09 has four roots in the interval - 1 lessthanorequalto x lessthanorequalto 3. Given the in-file fx.m, which contains function f = fx(x) f = sin (x.^2) + x.^2 - 2*x - 0.09; the statement >> brackPlot (\'fx\', -1, 3) however produces only two brackets. What needs to be changed so that all four roots are found? Demonstrate that your solution works.

Solution

Xb = brackPlot(’fx’,-1,3)

Xb = -0.1579 0.0526

2.1579 2.3684

returns two brackets.

A close inspection of the plot of f(x) reveals that f(x) crosses the x-axis twice near x = 1.3.

These two roots are missed by brackPlot because there default search interval is too coarse.

There is no bug in brackPlot. Implementing a solution using a finer search interval is left as an exercise

By, default it divides entire range into 20 points, so change it to more something like 200. Then you get the correct soultion.

Command is now changed to brackPlot(\'fx\',-1,3,200).

Now you get all the four roots of the equcation.

function Xb=brackPlot(fun,xmin,xmax,nx) % brackPlot: Find subintervals on x that contain sign changes of f(x) % Synposis: Xb=brackPlot(fun,xmin,xmax) % Xb=brack
function Xb=brackPlot(fun,xmin,xmax,nx) % brackPlot: Find subintervals on x that contain sign changes of f(x) % Synposis: Xb=brackPlot(fun,xmin,xmax) % Xb=brack

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site