My professor is having me write a program to perform the bisection routine to find the root of an equation. Before I go on, here are the program files so far:
function [l,r,nf] = bisect(fname,a,b,tol)
nf=0;
if (fname(a)*fname(b))>0
errflag='Choose an interval (a,b) where f(a)*f(b) is negative'
root='N/A'
else
while abs(fname(a)-fname(b))>tol
p=a+(b-a)/2;
if (fname(a)*fname(p))<0
b=p;
else
a=p;
end
nf=nf+1;
end
end
nf
l=a
r=b
end
Aside from the bisect.m file, he had us write a simple program fofx.m to evaluate the equation at whatever point. It looks like:
function [y]=fofx(x)
y=cos(x)-sin(x);
end
He wants us to have the fofx.m entered as an input argument so one can use any generic equation .m file. He has assigned us a test routine to operate the program. The test routine (which I am not allowed to change), is
try
delete('prog4run');
end
diary prog4run
format long e
[l,r,nfb] = bisect('fofx',0.7,0.9,1e-6);
p = l+(r-l)/2;
disp(' ')
disp(' ')
disp(' Bisect output:')
disp('root approx:'),p
disp(' ')
disp('error:'),abs(p-pi/4)
disp(' ')
disp('number of fcn evals:'),nfb
disp(' ')
disp(' ')
When I invoke the program in the command window by typing in:
bisect(@fofx,0.7,0.9,1e-6)
Bisect works perfectly. But when his test routine uses the line:
[l,r,nfb] = bisect('fofx',0.7,0.9,1e-6)
Even if I type this into the command window, I get the error:
Attempted to access fname(0.7); index must be a positive integer or logical.
Error in bisect (line 5)
if (fname(a)*fname(b))>0
Error in SCProg4Test (line 13)
[l,r,nfb] = bisect('fofx',0.7,0.9,1e-6);
Can anyone help me?
bisectfunction assumes that the first arg is a function handle, but apparently his test routine assumes that it's a string. Have you tried checking the type for the first arg and making it a function handle if it's not already. I don't have access to matlab right now, but something like this:if(ischar(fname)), eval( 'fhand = @(x)fname(x)' ); else fhand = fname; end