How does OR work in an IF statement?

1 次查看(过去 30 天)
I want the IF statement to check the value of 'Highest_value_month' and give 'Days' a value based on that, yet 'Days' always gets the value 31. As far as I know the syntax for OR is '||'. So why doesn't my IF statement work?
Highest_value_month = 6;
if Highest_value_month == 1 || 3 || 5 || 7 || 8 || 10 || 12
Days = 31;
elseif Highest_value_month == 2
Days = 28;
else
Days = 30;
end
The code is simplified in this case but it is essentially the same.

采纳的回答

Rik
Rik 2018-5-11
Because each is treated as separate test. Therefor you will need to use something like the line below. You could also use switch and case (see second example).
if Highest_value_month == 1 || ...
Highest_value_month == 3 || ...
Highest_value_month == 5 || ...
Highest_value_month == 7 || ...
Highest_value_month == 8 || ...
Highest_value_month == 10 || ...
Highest_value_month == 12
Days = 31;
end
or with switch:
switch Highest_value_month
case {1,3,5,7,8,10,12}
Days = 31;
case 2
Days = 28;
otherwise
Days = 30;
end

更多回答(1 个)

KSSV
KSSV 2018-5-11
编辑:KSSV 2018-5-11
Highest_value_month = 6;
val = [1 3 5 7 8 10 12] ;
if intersect(Highest_value_month,val)
Days = 31;
elseif Highest_value_month == 2
Days = 28;
else
Days = 30;
end
OR
Highest_value_month = 12;
val = [1 3 5 7 8 10 12] ;
if ismember(Highest_value_month,val)
Days = 31;
elseif Highest_value_month == 2
Days = 28;
else
Days = 30;
end

类别

Help CenterFile Exchange 中查找有关 Graphics Object Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by