MATLAB: Am I getting this error: Output argument (and maybe others) not assigned during call…

assignbisecterror

I am using a bisection method to find the roots of the function f(x)= cos(x) + ((1)/((x^3)+200)); I keep getting this error in my bisectscript:
"Output argument "c" (and maybe others) not assigned during call to…(the bisect function file) Error in bisectscript (line 5) [root,iteration] = bisect(f,a,b,tolerance);
Any help would be greatly appreciated!!
Thank you!
Script file:
f= @(x) cos(x) + ((1)/((x^3)+200));
a=-5;
b=5;
tolerance = 10e-10;
[root,iteration] = bisect(f,a,b,tolerance);
fprintf('The root is %12e8 \n', root)
Function File:
function [c,n] = bisect(f,a,b,tolerance)
fa =f(a);
fb =f(b);
s = sprintf ('You chose a wrong interval');
if(fa*fb >0)
display(s)
return;
end
maxit = 1 +round(log((b-a)/tolerance)/log(2));
for n = 1:maxit
c = (a+b)/2;
fc = f(c);
if(fc==0)
return
elseif (fb*fa<0)
a=c;
fa=fc;
else
b=c;
fb=fc;
end
end
end

Best Answer

I didn’t run your code, but this is likely the problem:
if(fa*fb >0)
display(s)
return;
end
Unless ‘fa’ or ‘fb’ are zero, the return statement exits your ‘bisect’ function and returns to the calling script. That occurs before ‘c’ and ‘n’ are assigned. That will throw the error because ‘bisect’ has no output to return.
Related Question