精简版
是否有比 ~isempty(x)
更简单的方法(如在其他语言中常见的那样)对非标量 x
进行“ bool 化”?
tl;dr 版本
在许多语言中,例如 Python,当在 bool 上下文中评估变量/符号时,它们会自动转换为 bool 标量。特别是,在这样的上下文中,类似列表的数据结构 x
如果为空则自动转换为 false,否则转换为 true。
这意味着可以使用列表作为操作数来编写任意 bool 表达式。例如:
>>> 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
在 MATLAB 中这不太行得通。例如
>> 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.
我能想到的最好的是这样的:
>> yesno = ~isempty(list1) && ~isempty(list2) && ~isempty(list3);
>> if yesno
true
else
false
end
ans =
1
是否有比 ~isempty(...)
更简单的符号来“ bool 化”a
MATLAB 数组?
最佳答案
isempty
实际上没有任何问题。
您可以使用这种方法来减少麻烦:
list1 = [1, 1];
list2 = [2, 2, 2];
list3 = [3, 3, 3, 3];
list4 = [];
yesno = all(~cellfun(@isempty, {list1,list2,list3,list4}))
如果您不介意重新组织数据,这是一个非常方便的选择:
lists{1} = [1, 1];
lists{2} = [2, 2, 2];
lists{3} = [3, 3, 3, 3];
lists{4} = [];
yesno = all(~cellfun(@isempty,lists))
关于matlab - 是否有比 `~isempty(x)` 更简单的方法将非标量 `x` 转换为 bool 标量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30052380/