Plotting Bisection intervals code

3 views (last 30 days)
gracias claude
gracias claude on 13 Feb 2021
Answered: Aashray on 26 Jun 2025
Looking for where I plot the intervals on a `plot()` and where ?
function [x,e] = MyBisectFunc(f, a1,b1, number)
format long
c1 = f(a1); d1 = f(b1);
if c1*d1 > 0.0
error ('Func has same sign at both endpoints')
end
for i = 1:number
x = (a1 + b1) /2;
y = f(x);
disp([x,y])
% tried this but nothing showed up on the graph
plot(x,y)
if abs(y) < 10^-8
break
end
if c1*y < 0
b1 = x;
else
a1 = x;
end
end
x = (a1 + b1)/2;
e = (b1 - a1) /2;

Answers (2)

Aashray
Aashray on 26 Jun 2025
I understand that you have implemented the bisection interval method for finding approximate roots. And that you are trying to plot how the interval [a, b] changes with each iteration, along with the midpoints. Here is how you can achieve that:
  1. Plot the function once for reference
  2. Add dynamic interval and mid-point plotting in the loop
function [x, e] = MyBisectFunc(f, a1, b1, number)
format long
c1 = f(a1); d1 = f(b1);
if c1 * d1 >= 0
error('Func has same sign at both endpoints or a root at endpoint');
end
figure
hold on
grid on
xlabel('x')
ylabel('f(x)')
title('Bisection Method Convergence')
% Plot the function for reference
x_vals = linspace(a1, b1, 500);
plot(x_vals, f(x_vals), 'k--', 'DisplayName', 'f(x)')
tol = 1e-8; % Tolerance for interval size
for i = 1:number
x = (a1 + b1) / 2;
y = f(x);
% Plot current midpoint, ensuring it persists
plot(x, y, 'ro', 'MarkerSize', 8);
delete(findobj('Type', 'line', 'Color', 'b'));
plot([a1, b1], [0, 0], 'b-', 'LineWidth', 1.5);
drawnow
if abs(y) < 1e-8 || (b1 - a1) / 2 < tol
break
end
if c1 * y < 0
b1 = x;
else
a1 = x;
end
pause(0.5);
end
x = (a1 + b1) / 2;
e = (b1 - a1) / 2;
end
f = @(x) x.^3 - 2;
[x_root, error_est] = MyBisectFunc(f, 1, 2, 25);
I have also attached the plots that I obtained by using the above code:

Harshavardhan
Harshavardhan on 24 Jun 2025
In MATLAB, the “plot(x, y)” command plots a single point or line segment, but it does not automatically retain previous points plotted in a loop. To continuously update the plot with each iteration, you need to use the "hold on” command, which tells MATLAB to retain the current plot and add new data to it.
To fix the issue:
  1. Add the following lines before the “for” loop:
figure; hold on; grid on;
xlabel('x'); ylabel('f(x)');
title('Bisection Method Iterations');
2. Replace “plot(x,y)” with:
plot(x, y,'ro'); % red circle for each iteration
For more information on “plot” and “hold” refer to their respective links below:

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!