How does OR work in an IF statement?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
0 Kommentare
Akzeptierte Antwort
Rik
am 11 Mai 2018
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
0 Kommentare
Weitere Antworten (1)
KSSV
am 11 Mai 2018
Bearbeitet: KSSV
am 11 Mai 2018
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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Graphics Object Programming finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!