if statement gives wrong results or does not work?

Hello,
I've got the following if statement within a for loop. In the beggining, i thought it's quite straight forward. I've got a scalar and an array, I have to compare each value of the array with that scalar and after that, to make certain calculations.
a_sat = -1.2;
a = [-5 -2 -7 0 -1 3 5];
for i = 1:length(a)
if a(1:length(a) ) >=a_sat
b = 0.45;
else if a(1:length(a)) < a_sat
b(i) = 3.*a;
end
end
end
This gives an undefined value of b. If I try to remove the counter in the if's, then I get a wrong result for the value of b. can anyone please help me with that? Thank you!

 採用された回答

Iain
Iain 2013 年 7 月 15 日

0 投票

"any" and "all" are your friends,
You have actually written
if ALL of a >= a_sat
set "b"
else, if ALL of a < sat
set "b"
else % (i.e. some of a > sat and some < sat)
do nothing
end
I don't know what you're actually wanting.
I suspect what you want is something like this
if a(i) > a_sat % if just the "ith" part of a is > a_sat
b = 0.45; % set b to "max"
else %if not...
b = 3*a(i); % b = 3* the "ith" part of a.
end

4 件のコメント

Christina
Christina 2013 年 7 月 15 日
Hi Iain
Yes, that's similar to what I need.
How will I use 'any' or 'all' for that purpose though?
Thank you
Iain
Iain 2013 年 7 月 15 日
It really depends on what you need.
if all( a >= a_sat ) %if all of a is greater/equal to a_sat
b = maxi;
else %under all other circumstances
b = something_else;
end
if any( a >= a_sat ) %if any of a is greater/equal to a_sat
b = maxi;
else % if none of a is greater/equal to a_sat
b = something_else;
end
What do you actually need?
Chin Wan Elijah
Chin Wan Elijah 2014 年 9 月 5 日
Hi Iain, I need something similar, but I have already put a 'min' in the 'if' condition, i.e. if min(result)<=-0.005 display('hello') end I checked the value for result, some of it actually fulfill the condition but there is no 'hello' displayed, what can this be caused by?
Iain
Iain 2014 年 9 月 5 日
If result is a matrix, when you take the min, you get a row vector. For that to go into the "then" part of the if statement, the ENTIRE row vector needs to be less than or equal to -0.005.

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

その他の回答 (0 件)

カテゴリ

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

質問済み:

2013 年 7 月 15 日

コメント済み:

2014 年 9 月 5 日

Community Treasure Hunt

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

Start Hunting!

Translated by