Azzera filtri
Azzera filtri

How does OR work in an IF statement?

2 visualizzazioni (ultimi 30 giorni)
Geriffa
Geriffa il 11 Mag 2018
Modificato: KSSV il 11 Mag 2018
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.

Risposta accettata

Rik
Rik il 11 Mag 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

Più risposte (1)

KSSV
KSSV il 11 Mag 2018
Modificato: KSSV il 11 Mag 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

Categorie

Scopri di più su Graphics Object Programming in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by