- must they all be empty except one?
- must they all be scalar?
- can they be non-scalar?
- etc. etc
Why can this expression be logically evaluated but not used in an if-statements?
조회 수: 2 (최근 30일)
이전 댓글 표시
If would like to make an if-statements that depends on the following condition:
nargin > 9 && cell2mat(varargin) == 1
To my disappointment, for nargin = 10 and varargin = 0, the expression can be evaluated with no problems in debugging mode when I run my function (the result being a logical 0). However, if I want to make an if-clause that starts with it, it throws an error message in the same line:
Operands to the logical AND (&&) and OR (||) operators must be convertible to logical scalar values.
Use the ANY or ALL functions to reduce operands to logical scalar values.
How can I deal with this and, more importantly, how can this even happen? If Matlab has a problem with my operands, how come it doesn't when I run it from the console?
댓글 수: 2
Stephen23
2023년 1월 13일
편집: Stephen23
2023년 1월 13일
"Why can this expression be logically evaluated but not used in an if-statements?"
The error has nothing to do with IF, as the error message states it is due to the inputs you provide to &&.
"How can I deal with this"
Perhaps you could follow the advice given in the error message.
But first you need to define what should happen when you collect multiple arguments with VARARGIN:
We cannot guess this for you. All we can see is that your code (apparently) concatenates multiple arrays (scalar, empty, we don't know because you did not say) into one array, which you then expect that array to be scalar. But it clearly isn't.
"how can this even happen?"
Because the inputs that you concatenate together create a non-scalar array. Take a look at this:
cell2mat({[],1,[],2}) % output is not scalar
답변 (1개)
Fangjun Jiang
2023년 1월 13일
편집: Fangjun Jiang
2023년 1월 13일
"somehow it didn't throw an error in any of the cases (1, any number or no number)."
- The coding problem still exists.
- The error happens when varargin is empty (an empty cell), see case 4
- The error didn't happen when varargin is empty, see case 3, is because the "false" ahead of "&&" operator. It is called short-circuiting. See "doc &&"
The better solution is to use isempty(varargin) to check if varargin is empty or not, first.
true && cell2mat({1})==1
true && cell2mat({0})==1
false && cell2mat({})==1
true && cell2mat({})==1
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!