フィルターのクリア

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

51 ビュー (過去 30 日間)
ad lyn
ad lyn 2021 年 10 月 29 日
コメント済み: ad lyn 2021 年 10 月 29 日
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.)
  1 件のコメント
ad lyn
ad lyn 2021 年 10 月 29 日
thank you!!!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by