repeat while loop with new boundary for x
Show older comments
function [r] = myroots(x,y,tol)
a = x(1);
b = x(end);
fprintf('Starting interval is from %f to %f \n', a, b)
error = b - a;
while abs(error) > tol
c = (a+b)/2;
if y(a)*y(c) < 0
b = c;
fprintf('New interval is from %f to %f \n', a, b)
error = b - a;
elseif y(b)*y(c) < 0
a = c;
fprintf('New interval is from %f to %f \n', a, b)
error = b - a;
elseif y(b)*y(c) > 0 && y(a)*y(c) > 0
a = c;
fprintf('New interval is from %f to %f \n', a, b)
error = b - a;
end
end
r = c;
end
Im trying to write a script to find root of a function y using the bisection method, this works as intended for small range of x (only one root within the interval). But when there're multiple roots (for function such as y = cos(x) or y = sin(x), etc) I only manage to get one root over a larger range of x (interval that covers multiple root), is there a way to rerun the loop again with new interval boundary for x? Example: after first run i found the highest root for x = 0:0.1:10, new interval to rerun with be x = 0:0.1:(highest root), so on and so on.
Thank you
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements 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!