Can you answer why am I getting this error. What should Ido? The error says 'Unrecognised variable z'.
2 views (last 30 days)
Show older comments
clear
clc
f=@(x) x+exp(x)-sin(x);
a=10;
b=12;
for i=1:50
c=((a*f(b)-b*f(a))/(f(b)-f(a)));
if abs(f(c))<0
a=c;
z=i;
break;
end
if f(a)*f(c)>0
b=c;
else
a=c;
end
end
fprintf('Regula Falsi Method');
fprintf('Approximate Root: %.6f\n',a);
fprintf('Iterations: %d.6f\n',z);
0 Comments
Answers (3)
Dyuman Joshi
on 18 Nov 2023
Edited: Dyuman Joshi
on 18 Nov 2023
"Can you answer why am I getting this error."
Because "z" has not been defined.
Two things - Firstly, you are assuming that the root will be found within 50 iterations, which is not guaranteed. A while loop is a better option here.
Secondly, the criteria for stopping the false position method is f(c)==0, not the absolute value less than zero (which is, quite obviously, never going to happen). So change that. And as you are dealing with floating point numbers, it is best to compare using a tolerance.
clear
clc
f=@(x) x+exp(x)-sin(x);
a=10;
b=12;
i=0;
while 1
c=((a*f(b)-b*f(a))/(f(b)-f(a)));
%comparing using a tolerance
if abs(f(c))<1e-6
a=c;
%z is not needed as you can directly use i
%z=i;
break;
end
if f(a)*f(c)>0
b=c;
else
a=c;
end
i=i+1;
end
Also, you can combine the fprintf() statements -
fprintf('Regula Falsi Method\nApproximate Root: %.6f\nIterations: %d\n', a, i);
Now, compare the output obtained from the Regula falsi method to the output from fzero (just for a check) -
fprintf('%0.6f', fzero(f, a))
Extremely close. I'd say the code is working properly now.
0 Comments
Star Strider
on 18 Nov 2023
The first if block condition is not being satisfied, so ‘z’ is not defined.
The reason is easy to see, since any absolute value will always be positive, so the test that ‘abs(f( c ))<0’ will always fail.
0 Comments
Image Analyst
on 18 Nov 2023
If youi knew how to debug, you wouldn't need to ask why z never got assigned. You would step through your code, like the rest of us do, and notice that you never hit the z line.
0 Comments
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!