Weird errors with functions and while loops

Hi, I had question about my code. I'm trying to make a code that basically finds the root of a polynomial through the bisection method. However, there are a few errors with my code that I'm not sure how to fix. My while loop is giving me an error, saying that 'p' was used before it was defined. However, I defined it above. Also, the line of code where I called on the function ([root,flag]=bisect(a,b,c,d,A,B)) is giving me an error, but Matlab doesn't specify the error. It just says that there is one. Here's my code down below. Any help would be great, thank you.
a = -1;
b = 1;
c = -1;
d = 10;
A = 0;
B = 5;
p=1;
[root]=bisect(a,b,c,d,A,B);
function [root]=bisect(a,b,c,d,A,B)
pol=@(x) a*x^3+b*x^2+c*x+d;
mid=(A+B)/2;
while p==1
if pol(mid)==0
root=mid;
elseif (pol(mid)*pol(B))<0
A=mid;
elseif (pol(mid)*pol(A))<0
B=mid;
end
if pol(mid)==0
p=0;
end
end
end

Answers (1)

Jan
Jan on 31 May 2019
Edited: Jan on 31 May 2019
Please post the original error messages instead of only a rephrased part of it.
"My while loop is giving me an error, saying that 'p' was used before it was defined. However, I defined it above" - You have defined p in the script, but each function has its own workspace, such only the provided input arguments are visible inside. Simply move "p=1;" inside the function, before the while loop.
Currently mid is computed once before the loop, but the bisection is an iterative process, which must update mid. Another problem is, that you cannot expect mid to be exactly 0.0 due to rounding errors. You need to accept a root with a certain limit:
if abs(pol(mod)) < 1e-8
"Also, the line of code where I called on the function ([root,flag]=bisect(a,b,c,d,A,B)) is giving me an error, but Matlab doesn't specify the error. It just says that there is one." - The line
[root,flag]=bisect(a,b,c,d,A,B)
does not occur in the posted code. Please post the code your are talking of and not another one. I'm sure, that the error message is not "there is one". Take care to post exactly, which messages you get where. It is easier to fix a problem than to guess, what the problem is. What let you assume that which code contains an error?

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Asked:

on 31 May 2019

Edited:

Jan
on 31 May 2019

Community Treasure Hunt

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

Start Hunting!