Evaluate Multiple Conditions in Expression

조회 수: 8 (최근 30일)
Roger Breton
Roger Breton 2022년 1월 9일
댓글: the cyclist 2022년 1월 11일
I've been meaning to simplify my code by combining multiple conditions into one IF statement.
This is what I'm currently using :
if IntX < 1
ah.Color=[1, 1, 1];
xlabel(ax, ' ');
return;
end
if IntX > Inner(3)
ah.Color=[1, 1, 1];
xlabel(ax, ' ');
return;
end
if IntY < 1
ah.Color=[1, 1, 1];
xlabel(ax, ' ');
return;
end
if IntY > Inner(4)
ah.Color=[1, 1, 1];
xlabel(ax, ' ');
return;
end
This is not elegant but it works. I experimented with this statement but I get an error :
if (IntX < 1) && (IntX > Inner(3)) && (IntY < 1) && (IntY > Inner(4))
ah.Color=[1, 1, 1];
xlabel(ax, ' ');
return;
end
  댓글 수: 2
Torsten
Torsten 2022년 1월 9일
Use || instead of &&
Voss
Voss 2022년 1월 9일
If either of IntX and IntY is a vector, you'll get an error using && or ||.

댓글을 달려면 로그인하십시오.

채택된 답변

the cyclist
the cyclist 2022년 1월 9일
if (IntX < 1) | (IntX > Inner(3)) | (IntY < 1) | (IntY > Inner(4))
ah.Color=[1, 1, 1];
xlabel(ax, ' ');
return;
end
You should also be able to use the short-circuit operator || instead of |.
  댓글 수: 2
Roger Breton
Roger Breton 2022년 1월 11일
편집: Roger Breton 2022년 1월 11일
Works like a charm -- thank you!
I'm not sure I'm clear on the short-circuit operator : is that, as soon as one condition is false, the whole expression stops being evaluated?
the cyclist
the cyclist 2022년 1월 11일
You have the gist right, but in the short-circuited OR operation, it will evaluate from left-to-right until it finds a TRUE condition, because then it knows the entire expression is true.
See a fuller explanation in this section of the documentation.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by