- 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 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Stephen23
am 13 Jan. 2023
Bearbeitet: Stephen23
am 13 Jan. 2023
"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
Antworten (1)
Fangjun Jiang
am 13 Jan. 2023
Bearbeitet: Fangjun Jiang
am 13 Jan. 2023
"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 Kommentare
Siehe auch
Kategorien
Mehr zu Structures finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!