I am trying to error of bisection method using matlab with stem
the error is calculated for each iteration by abs(x2-x1), so I need to draw it using stem
the output must be something like that:
this is my code:
close all; clear ; clc;
syms x;
f=@(x)(x^(2))-(2);
x1=1;
x2=2;
acc=10^(-8);
n=0;
disp (' Bisection Method')
disp ('===========================================')
disp ('iteration root(P-hat) error')
while (abs(x2-x1)>acc)
n = n + 1;
xm=(x1+(x2-x1)/2);
if (f(x1)*f(xm)<0)
x2=xm;
else
x1=xm;
end
figure(1)
X = linspace(0,30);
Y = abs(x2-x1);
stem(X,Y);
grid on
hold on
fprintf('%3d %20.8f %20.10f \n', n, xm, abs(x2-x1));
end
and this error is showing for me:
Bisection Method
===========================================
iteration root(P-hat) error
Error using stem (line 43)
X must be same length as Y.
Error in Ass1Bisection (line 28)
stem(X,Y);
as you can seen, the values of the iterations, root, and error that not printed even because of this error
how may I solve it?
In this case Y is created empty and the instruction Y(end+1)
will make it to add one element.
close all; clear ; clc;
syms x;
f=@(x)(x^(2))-(2);
x1=1;
x2=2;
acc=10^(-8);
n=0;
disp (' Bisection Method')
disp ('===========================================')
disp ('iteration root(P-hat) error')
Y = []
while (abs(x2-x1)>acc)
n = n + 1;
xm=(x1+(x2-x1)/2);
if (f(x1)*f(xm)<0)
x2=xm;
else
x1=xm;
end
figure(1)
Y(end+1) = abs(x2-x1);
stem(1:length(Y),Y);
grid on
hold on
fprintf('%3d %20.8f %20.10f \n', n, xm, abs(x2-x1));
end