Printing iterations in while loop

12 ビュー (過去 30 日間)
Nicholas Fornaciari
Nicholas Fornaciari 2019 年 6 月 3 日
コメント済み: Stephen23 2019 年 6 月 4 日
I've been trying to print each iteration of this loop without any sucess. I've tried various verison of fprintf even setting a blank variable to display after and it never works.
myfunction = @(x) x^2-2;
i = 0;
xl = input('X upper ');
xu = input('X lower ');
xmid = (xl+xu)/2;
fprintf('\tI \txl \txu \txmid')
while i > 100
if (myfunction(xmid) * myfunction(xu))<0
xl = xmid;
else
xu = xmid;
end
xmid = (xl + xu)/2;
i = i+1;
fprintf('\n \n \n \n',i, xl,xu,xmid)
end

回答 (1 件)

Stephen23
Stephen23 2019 年 6 月 3 日
編集済み: Stephen23 2019 年 6 月 3 日
Your second fprintf simply prints four newlines, and ignores its inputs. As the fprintf documentation shows, you need to include some numeric conversion format operators in order to print the values of any variables, e.g.:
fprintf('\t%g\t%g\t%g\t%g\n',i,xl,xu,xmid)
Note that you define
i=0
and then you define the loop with:
while i > 100
but the condition is not true, so your loop will not even iterate once.
  2 件のコメント
Nicholas Fornaciari
Nicholas Fornaciari 2019 年 6 月 3 日
How would i go about changing the formula so it does it for a certain number of iterations?
Stephen23
Stephen23 2019 年 6 月 4 日
"How would i go about changing the formula so it does it for a certain number of iterations?"
Use a for loop:
for k = 1:100
...
end

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

カテゴリ

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