while loops

8 ビュー (過去 30 日間)
marvin corado
marvin corado 2011 年 3 月 5 日
回答済み: Van 2014 年 12 月 17 日
First time posting. Excuse if i do not post correctly. My problem is with a while loop. I created my self a short while loop test just to see how it works. i run it and it does what i want. that is to say increase mx by 1 until it hits 3, and then when sum is equal to summ, it performs a. here is what i wrote.
mx=1;
while mx<3.0 mx=mx+1; sum=mx*2; summ =4; if (sum==summ) break a=2*sum end end
My problem is that when i increase mx by 0.1 matlab does not perform the if statement. I know sum and summ will be equal at some point but matlabd never performs a. Any help? thank you.

採用された回答

Matt Fig
Matt Fig 2011 年 3 月 5 日
Also, you might find Cleve's article interesting.
.
.
.
mx=1;
tol = 1e-8;
while mx<3.0
mx=mx+1;
sum=mx*2;
summ =4;
if abs(sum-summ)<tol
a=2*sum
break
end
end

その他の回答 (5 件)

Walter Roberson
Walter Roberson 2011 年 3 月 5 日
You will find an explanation at this FAQ
By the way, it is a bad practice to name one of your variables with the name of one of the built-in routines such as "sum". Don't make a habit of it or else it will cause you problems later -- problems that you will stare at and stare at and not see because you "know" what you mean the code to do.

marvin corado
marvin corado 2011 年 3 月 5 日
sorry i meant to put it like this.
mx=1;
while mx<3.0
mx=mx+1;
sum=mx*2;
summ =4;
if (sum==summ)
break
a=2*sum
end
end
  1 件のコメント
Walter Roberson
Walter Roberson 2011 年 3 月 5 日
You can go back and edit your question. Just select your code and click on the "Code {}" button.

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


marvin corado
marvin corado 2011 年 3 月 5 日
ok i read it and its helpful. I tried implementing a solution by using
areEssentiallyEqual = abs(a-b) < tol
like they say, but cant seem to get it working where would the fix above be placed ?

marvin corado
marvin corado 2011 年 3 月 5 日
ok what would establish the tol.. is it something i choose or something that needs to be calculated? thank you
  2 件のコメント
Matt Fig
Matt Fig 2011 年 3 月 5 日
Just like in my example above, tol is something you choose.
Walter Roberson
Walter Roberson 2011 年 3 月 5 日
Choosing a tolerance is fine if you know something about the floating point representation of the range of values you are using, but for more general usage the tolerance should usually be based upon eps() of the maximum magnitude of the values you are working with.

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


Van
Van 2014 年 12 月 17 日
I think the problem is the positioning. Isn't that the "a=2*sum" should be placed above the break?
%
mx=1;
while mx < 3.0
mx=mx+1;
sum=mx*2;
summ =4;
if (sum==summ)
a = 2*sum
break
end
end
which will result to 8. I hope i answer it correctly.

カテゴリ

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