what does the expression " if ( ) && ( ) " do
조회 수: 51 (최근 30일)
이전 댓글 표시
if (i>=njmp1) && (i<=njmp2)
fcs(i)=a*i+b;
elseif (i>njmp2)
fcs(i)=fc2;
end
댓글 수: 0
채택된 답변
추가 답변 (1개)
Walter Roberson
2021년 10월 29일
Except for line numbering and issues about when interruptions are permitted, the code you posted is equivalent to
if (i>=njmp1)
if (i<=njmp2)
fcs(i)=a*i+b;
elseif (i>njmp2)
fcs(i)=fc2;
else
%do nothing
end
elseif (i>njmp2)
fcs(i)=fc2;
else
%do nothing
end
complete with the implication that i<=njmp2 will not be executed at all if i>=njmp1 is false.
Imagine that you have a situation where you have a variable in which a non-nan second element is to be used, provided that a second element exists:
ub = inf;
if length(bounds) > 1
if ~isnan(bounds(2))
ub = bounds(2);
end
end
this cannot be coded as
ub = inf;
if length(bounds) > 1 & ~isnan(bounds(2))
ub = bounds(2);
end
because the & operator always evaluates all if its parts, and so would always try to access bounds(2) even if length(bounds)>1 were false. The & operator is not smart about stopping if the condition cannot be satisfied. But
ub = inf;
if length(bounds) > 1 && ~isbounds(2))
ub = bounds(2);
end
is fine. The && operator is smart about not evaluating the second operand if the first is false -- not just "smart" but guarantees that the second part will not be evaluated. (In such a situation to just say it was "smart" implies that it is a matter of optimization, that it thinks it is "more efficient" not to evaluate the second operand -- but that implies that in some circumstances, perhaps involving parallel processing, if it happened to be more efficient to evaluate the second clause, that it could potentially be evaluated. But the && operand promises that the second operand will not be evaluated if the first one is false, so it is safe to use && with chains of tests that rule out the possibility of exceptional behaviour.)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!