MATLAB: How to make a table bisection method and put all iterables step by step

bisection methodnumerical analysis

a = input('a = ');
b = input('b = ');
E = input('Error = ');
N = log((b-a)/E)/(log(2))
f = @(x) x^2 - 3;
format long
for i = 1:N
c =(a+b)/2;
T = table(N,a,b,c,f(c));
T(N:5,:)
disp(T);
if f(c) * f(a) > 0
a = c;
else
b = c;
end
% if (abs(b-a) / 2^N) <= E || f(c) == 0
% break
% end
end
final_ans = c;
fprintf('root is %f\n',final_ans);
% OUTPUT
%N a b c Var5
%________________ _______ ____ ________ ______________
%7.64385618977472 1.71875 1.75 1.734375 0.008056640625
%root is 1.734375

Best Answer

With your current method the table is overwritten in each iteration. Create the table before the loop and insert the new values only.
[EDITED] Some code:
a = 1;
b = 2;
E = 1e-6;
N = ceil(log((b - a) / E) / log(2)); % CEIL() !
f = @(x) x^2 - 3;
T = table('Size', [N, 5], ...
'VariableTypes', {'double', 'double', 'double', 'double', 'double'}, ...
'VariableNames', {'N', 'a', 'b', 'c', 'fc'});
for i = 1:N
c = (a + b) / 2;
T(i, :) = {i, a, b, c, f(c)}; % Fill in data in existing table
if f(c) * f(a) > 0
a = c;
else
b = c;
end
end
disp(T)