필터 지우기
필터 지우기

How does OR work in an IF statement?

조회 수: 1 (최근 30일)
Geriffa
Geriffa 2018년 5월 11일
편집: KSSV 2018년 5월 11일
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