Matlab:断言(数组)与 if(数组)

Matlab: assert(array) vs if (array)

在 Matlab 中(截至 2016a)条件 if (array_of_logicals) 在功能上等同于 if (all(array_of_logicals))documentation 表示:"An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric)."

另一方面,assert() only accepts a "Condition to assert, specified as a valid MATLAB expression." 根据实验,这意味着 array_of_logicals 应该用作 assert(all(array_of_logicals))

您认为行为略有不同的原因是什么?

我知道一个原因可能是 assert() 你想排除 assert(all(array_of_logicals))assert(any(array_of_logicals)) 的解释歧义, 但对于 if.

也可以这样说

编辑:我特别想了解为什么为 if 选择此行为。

如果您在代码中使用 assert,您希望绝对确定给定条件为真,其中一部分是消除真定义中的任何歧义。通过要求 logical 标量,assert 迫使用户准确确定他们的期望。这也确保了如果出于某种原因 MATLAB 想要更改它们将任意数据转换为 logical 标量的方式,您的 assert 调用将不受影响。

至于为什么 if 不需要明确的 logical 标量,我不确定,但这可能只是为了简化编码,特别是当 MATLAB 使用 double默认数据类型

condition = 1

% This will fail since condition is a double not a logical value
assert(condition)

% This won't work if you required explicit logical scalars
if condition
end

assert 的目的是执行执行测试,因此将其编码为期望代表测试结果的真/假输入(即 "logical scalar")是合理的,而不是任何非零数组。 if 可以更通用,因为它更有可能接收矩阵比较表达式而不是执行/验证测试。

但是,老实说,我怀疑这个决定背后并没有什么有见地的天才。两者可能只是碰巧独立实施,并根据上下文做出决定。

if 行为并不新鲜,从我记事起就是这样。在我的 2013a 上:The statements are executed if the real part of the expression has all non-zero elements。而对于 assert 它只是说:evaluate EXPRESSION and, if it is false...

有趣的是,octave并没有选择以同样的方式实现assert。在 Octave 中,此测试将通过:assert([1,1]==[1,1]);