Search code examples
matlabsyntaxcastingshortcutnotation

Is there something simpler than `~isempty(x)` to cast a non-scalar `x` into a boolean scalar?


short version

Is there a less cumbersome way (as is found commonly in other languages) to "booleanize" a non-scalar x than ~isempty(x)?


tl;dr version

In many languages, such as Python, when variables/symbols are evaluated in a boolean context they are automatically cast to a boolean scalar. In particular, in such a context, a list-like data structure x is automatically cast to false if it is empty, and to true otherwise.

This means that one can write arbitrary boolean expressions using lists as operands. For example:

>>> list1 = [1, 1]
>>> list2 = [2, 2, 2]
>>> list3 = [3, 3, 3, 3]
>>> yesno = list1 and list2 and list3
>>> if yesno:
...   print True
... else:
...   print False
... 
True

In MATLAB this doesn't quite work. For example

>> list1 = [1 1];
>> list2 = [2 2 2];
>> list3 = [3 3 3 3];
>> yesno = list1 && list2 && list3;
Operands to the || and && operators must be convertible to logical scalar values. 
>> yesno = list1 & list2 & list3;
Error using  & 
Matrix dimensions must agree. 

The best I can come up with is something like this:

>> yesno = ~isempty(list1) && ~isempty(list2) && ~isempty(list3);
>> if yesno
  true
else
  false
end
ans =
     1

Is there a less cumbersome notation than ~isempty(...) for "booleanizing" a   MATLAB array?


Solution

  • Short: No, there isn't and ~isempty() is fine coding. You could shorten it slightly by

    yesno = ~isempty(l1)*~isempty(l2)*~isempty(l3)
    

    cheers