I used a code for bisection method, which supposed to be working, unfortunately it´s not and I do not know what is the problem. This code also includes user defined precision and a counter for number of iterations. The error I´m getting is for the last line in the code: Undefined function or variable 'c'.
a=-5;
b=0;
tol = input('What precision would you like? ','s')
fa=a^3-20+exp(a);
fb=b^3-20+exp(b);
counter=1
while abs(b-a) > tol
c=(a+b)/2;
fx = c*c-2;
if fa*fc<0
b=c;
fb=fc;
elseif fb*fc<0
a=c;
fa=fc;
else
break
end
fprintf('Just finished iteration #%d\n', counter);
counter=counter+1;
end
x=c;

 Accepted Answer

NEVER hard code a function. Outside of the loop, you appear to be tring to solve the function
x^3 - 20 + exp(x) == 0
Inside of the loop, you are trying to solve the problem
x^2 - 2 == 0
So even if this ever somehow incorrectly did terminate, you would get garbage for a result.
Learn how to use a function handle. Or learn how to define a function.
The real reason why your code failed? I think you don't understand how to use input. READ THE HELP!
tol = input('What precision would you like? ','s')
What precision would you like? 0.001
tol =
'0.001'
So I provided a tolerance of 0.001. But did MATLAB understand me? Because when you used input, you told MATLAB to accept the result as a string!
whos tol
Name Size Bytes Class Attributes
tol 1x5 10 char
So tol is the character string '0.001'. tol s NOT a number. Is there a good reason why you used input in that way? NO.
READ THE HELP FOR TOL.
help tol

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!