what does the expression " if ( ) && ( ) " do

94 次查看(过去 30 天)
if (i>=njmp1) && (i<=njmp2)
fcs(i)=a*i+b;
elseif (i>njmp2)
fcs(i)=fc2;
end

采纳的回答

James Tursa
James Tursa 2021-10-29
&& is the "logical and" operator. You can read about it here:
  1 个评论
ad lyn
ad lyn 2021-10-29
but when we use it in the previous statement is it gonna keep the "AND" fonctionnality?

请先登录,再进行评论。

更多回答(1 个)

Walter Roberson
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 CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by