How can I make a table bisection method and put all iterables step by step?
5 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Jan
on 31 Mar 2021
Edited: Jan
on 31 Mar 2021
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)
2 Comments
Jan
on 31 Mar 2021
Edited: Jan
on 31 Mar 2021
"i tried to put the table before the loop" - Then please post the corresponding code. This is more efficient for solving your problem than letting the readers guess, what you have done exactly.
I still do not like the table syntax and avoid using this type in productive code. But see [EDITED] in my answer for an explicit example.
More Answers (0)
See Also
Categories
Find more on Whos 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!