Why do I get this result??

2 ビュー (過去 30 日間)
Carole
Carole 2012 年 11 月 7 日
Hello
I have a problem with this code
k=2*A+3*B
if k<3.65
fr='inf'
elseif 3.65<k<=4.35
fr='moy'
elseif k>4.35
fr='sup'
end
why i get this result 'moy'?? it must be 'sup'
k =
6.4582
fr =
moy
Can you help me to correct this code.

採用された回答

Evan
Evan 2012 年 11 月 7 日
編集済み: Evan 2012 年 11 月 7 日
The below line is the culprit:
elseif 3.65<k<=4.35
Specifying inequalities in matlab isn't done in the same notation as you might when writing them. If you need to find when a value is between an upper and lower bound, do something like this:
elseif 3.65 <= k && k <= 4.35
The way you have it, matlab evaluates the statement from left to right. So, if k = 6.4582, these will be the steps matlab performs:
1. (3.65 < k) <= 4.35
2. (1) <= 4.35
3. 1
Because the expression in parenthesis is true, it evaluates to "1." This leaves 1 <= 4.35, which will also return 1. But your value was 6.4582, meaning the code didn't do what you intended!
Instead, include each condition in your if statement, separating them with && symbols.

その他の回答 (2 件)

David Barry
David Barry 2012 年 11 月 7 日
Try this
k=2*A+3*B
if k<3.65
fr='inf'
elseif k >= 3.65 && k<= 4.35
fr='moy'
elseif k>4.35
fr='sup'
end
  3 件のコメント
David Barry
David Barry 2012 年 11 月 7 日
Also note that I have changed your code to cope when k = 3.65
Evan
Evan 2012 年 11 月 7 日
Good catch. I didn't notice that. I've updated my post to account for that issue, but credit goes to you. :)

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


Sean de Wolski
Sean de Wolski 2012 年 11 月 7 日

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by