Azzera filtri
Azzera filtri

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

51 visualizzazioni (ultimi 30 giorni)
ad lyn
ad lyn il 29 Ott 2021
Commentato: ad lyn il 29 Ott 2021
if (i>=njmp1) && (i<=njmp2)
fcs(i)=a*i+b;
elseif (i>njmp2)
fcs(i)=fc2;
end

Risposta accettata

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

Accedi per commentare.

Più risposte (1)

Walter Roberson
Walter Roberson il 29 Ott 2021
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.)

Community Treasure Hunt

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

Start Hunting!

Translated by