fprintf into a stored variable

1 回表示 (過去 30 日間)
WhatIsMatlab-
WhatIsMatlab- 2016 年 2 月 12 日
コメント済み: per isakson 2016 年 2 月 15 日
Instead of using fprintf I want to store all the i, xe, and f(xe) into a vector instead. That way I can call them later. Also I had another problem where I wanted to use another 'i' later on in the code. But it only allowed me to use 1. How can you use two different 'i's. So they don't get mixed up.
f = @(x) x^2-6;
xl = 0;
xu = 10;
xe = (xu+xl)/(2);
acc = 0.00001;
while abs(f(xe))> acc
i = i + 1;
fprintf('%d)\t%f\tf(x)=%f\n',i,xe,f(xe));
if (f(xe)*f(xl)) < 0
xu = xe;
else
xl = xe;
end
xe = (xu+xl)/2;
end

採用された回答

per isakson
per isakson 2016 年 2 月 13 日
編集済み: per isakson 2016 年 2 月 13 日
Add
M = zeros( 0, 2 );
before the loop and replace
fprintf('%d)\t%f\tf(x)=%f\n',i,xe,f(xe));
by
M( end+1, 1:2 ) = [ xe, f(xe) ];
You'll get a warning about "Growing ..." , but if speed is acceptable ignore it.
&nbsp
"fprintf into a stored variable" &nbsp If understood literally, replace
fprintf('%d)\t%f\tf(x)=%f\n',i,xe,f(xe));
by
C{end+1,1} = sprintf('%d)\t%f\tf(x)=%f\n',i,xe,f(xe));
and add C=cell(0,1) before the loop
  10 件のコメント
per isakson
per isakson 2016 年 2 月 15 日
  • "but I got an error" &nbsp we cannot help if you don't show what you did and what error Matlab reported.
  • "a better way of achieving this" &nbsp length(s) and length(m) tell the number of iterations in the two loops.
per isakson
per isakson 2016 年 2 月 15 日
This example illustrates
  • two ways to count the number of loop iterations
  • two ways to store result in the loop
N = 1e6;
M1 = zeros( 0 );
ii = 0;
M2 = nan( N, 1 ); % Pre-allocate
while sqrt(ii) < sqrt(N) - 10
ii = ii + 1;
M1( end+1, 1 ) = ii;
M2(ii) = ii;
end
M2(isnan(M2)) = [];
disp( all( M2 == M1 ) )
disp( ii )
disp( length(M1) )
disp( length(M2) )
outputs
1
980100
980100
980100
where "1" shows that M1 and M2 are identical.
[Run and Time], i.e. the profiler, shows that "M1" is slower.

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

その他の回答 (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