Hi, I am trying to test out an iterative process to converge on one value. I am trying to use while and if statements to converge on a test value of 5; however, my process causes matlab to infinitely loop between 5.00 and 5.100 rather than stopping at 5. My code is below and any advice would be much appreciated. Thanks in advance.
J. Ryan Kersh
while n~= 5
if n<5
n=n+.1
end
if n>5
n=n-.1
end
end

1 件のコメント

Yatin
Yatin 2013 年 10 月 14 日
What is the initial value of n that you are using? Based on your increments, I think that your values of n would be typically oscillating between some constant values around 5.00. May be using function like abs(), floor(), ceil() will be useful in this case for convergence.

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

 採用された回答

Cedric
Cedric 2013 年 10 月 14 日
編集済み: Cedric 2013 年 10 月 14 日

1 投票

You have to think again about the condition in the WHILE statement or about the increments that you are using. To see why, assume that you are starting with n = 4.95, and generate a few iterations by hand.
You could make increments proportional to the difference between 5 and n, e.g. n=n+(5-n)/2, and implement some tolerance in the condition of the while statement, e.g. abs(5-n)>1e-3.

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2013 年 10 月 14 日

コメント済み:

2013 年 10 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by