Whats wrong with this operator?

1 回表示 (過去 30 日間)
Mr M.
Mr M. 2017 年 7 月 21 日
コメント済み: Steven Lord 2017 年 7 月 22 日
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 件のコメント
Mr M.
Mr M. 2017 年 7 月 22 日
i1, trial, x, x0 all scalars!
Steven Lord
Steven Lord 2017 年 7 月 22 日
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

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

回答 (2 件)

Star Strider
Star Strider 2017 年 7 月 21 日
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 2017 年 7 月 21 日
編集済み: John D'Errico 2017 年 7 月 21 日
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.

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by