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

5 ビュー (過去 30 日間)
Mahdi Ayyad
Mahdi Ayyad 2021 年 3 月 31 日
編集済み: Jan 2021 年 3 月 31 日
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

採用された回答

Jan
Jan 2021 年 3 月 31 日
編集済み: Jan 2021 年 3 月 31 日
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 件のコメント
Mahdi Ayyad
Mahdi Ayyad 2021 年 3 月 31 日
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 2021 年 3 月 31 日
編集済み: Jan 2021 年 3 月 31 日
"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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by