Whats wrong with this operator?

12 vues (au cours des 30 derniers jours)
Mr M.
Mr M. le 21 Juil 2017
Commenté : Steven Lord le 22 Juil 2017
Operands to the || and && operators must be convertible to logical scalar
values.
Error in optscan (line 114)
if (i1 == 1) && (trial == 1) && (x < 0.5*x0)
  2 commentaires
Mr M.
Mr M. le 22 Juil 2017
i1, trial, x, x0 all scalars!
Steven Lord
Steven Lord le 22 Juil 2017
Show us the size and class of the variables. Paste the output of the following command, executed immediately before line 114 of optscan executes, into a comment on this Answer.
whos i1 trial x x0

Connectez-vous pour commenter.

Réponses (2)

Star Strider
Star Strider le 21 Juil 2017
Without seeing more of your code, it is likely that this test:
(x < 0.5*x0)
is not a logical scalar value.
If you want to test that any of the values of vector ‘x’ are less than 0.5*x0, use the any function:
single_scalar_value = any(x < 0.5*x0)
That test would be compatible with the ‘&&’ operator.

John D'Errico
John D'Errico le 21 Juil 2017
Modifié(e) : John D'Errico le 21 Juil 2017
READ THE ERROR MESSAGE!!!!!!!!!
"Operands to the and && operators must be convertible to logical scalar values. Error in optscan (line 114) if (i1 == 1) && (trial == 1) && (x < 0.5*x0)"
Is i1 a scalar variable? If not, then what does the error message tell you?
Is trial a scalar variable? See above.
Is x a scalar variable? See above.
Is x0 a scalar variable? See above.
If any of those variables are not scalars, then they will result in a vector or array result.
So, why is this a problem? The and && operators are short-circuited tests. They are used typically in if statements, or whiles. When you use a construct like this:
if A && B
stuff
end
Suppose that A is false? Do you really need to check on the value of B? Of course not, since we will go through only if both of them were true. So && is used as a short-circuited operator. But what if one of A or B is a vector or an array? Then some elements may be true, some false. MATLAB would be unable to proceed.
So read the error message. It told you of this problem.
Learn to use the debugger. Look at your code.

Catégories

En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by