How does OR work in an IF statement?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuesta aceptada
Rik
el 11 de Mayo de 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 comentarios
Más respuestas (1)
KSSV
el 11 de Mayo de 2018
Editada: KSSV
el 11 de Mayo de 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 comentarios
Ver también
Categorías
Más información sobre Graphics Object Programming en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!