matlab - 是否有比 `~isempty(x)` 更简单的方法将非标量 `x` 转换为 bool 标量?

标签 matlab syntax casting shortcut notation

精简版

是否有比 ~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))

cellfun的组合和 isempty应该非常快,尽管我现在缺少此声明的来源。

关于matlab - 是否有比 `~isempty(x)` 更简单的方法将非标量 `x` 转换为 bool 标量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30052380/

相关文章:

c - C中正态分布的错误答案

matlab - 如何在MATLAB中从人脸图像中提取LBP特征?

r - 作为参数传递以应用函数的带引号的方括号的确切含义是什么?

C : Parse Hex string to unsigned long

casting - 如何安全地、惯用地在数字类型之间进行转换?

linux - 将 .m 库打包到 MATLAB 可执行文件中

Matlab:直方图数据与许多高斯和 AIC 评估的拟合

excel - 试图在单元格中找到精确字符串的下一个实例

MySQL - 查询与其ID对应的不同表的名称

模板类的 C++ 转换