How can I make a table bisection method and put all iterables step by step?

5 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Jan
Jan il 31 Mar 2021
Modificato: Jan il 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 Commenti
Mahdi Ayyad
Mahdi Ayyad il 31 Mar 2021
But this is the output
% OUTPUT
%N a b c Var5
%________________ _______ ____ ________ ______________
%7.64385618977472 1.71875 1.75 1.734375 0.008056640625
%root is 1.734375
it's not overwritten, but i tried to put the table before the loop and still the same.
Jan
Jan il 31 Mar 2021
Modificato: Jan il 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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by