今天我很惊讶地发现
A = {1,2,3}
和
B = {1,2,3,}
都是 MATLAB 中的有效语法。我本以为第二条语句会产生错误。据我所知,它们生成相同的元胞数组(all([A{:}]==[B{:}])
返回 true)。
是否有允许第二种语法的原因?这是解析器中的错误吗? A
和 B
真的一样吗?
有趣的是,不允许以下内容:
C = {1,2,3,,,}
最佳答案
这些是更多的猜测,而不是答案。
可以检查 Symbol reference并发现 逗号 ,
可以用作
命令或语句分隔符
To enter more than one MATLAB command or statement on the same line, separate each command or statement with a comma:
for k = 1:10, sum(A(k)), end
在行中
B = {1,2,3,}
因此 3
之后的语句是预期的,只有 ,这意味着 元胞数组结束,一个有效的语句。
分号;
官方有3种用法:
数组行分隔符
When used within square brackets to create a new array or concatenate existing arrays, the semicolon creates a new row in the array:
A = [5, 8; 3, 4]
输出抑制
When placed at the end of a command, the semicolon tells MATLAB not to display any output from that command. In this example, MATLAB does not display the resulting 100-by-100 matrix:
A = ones(100, 100);
命令或语句分隔符
Like the comma operator, you can enter more than one MATLAB command on a line by separating each command with a semicolon. MATLAB suppresses output for those commands terminated with a semicolon, and displays the output for commands terminated with a comma.
In this example, assignments to variables A and C are terminated with a semicolon, and thus do not display. Because the assignment to B is comma-terminated, the output of this one command is displayed:
A = 12.5; B = 42.7, C = 1.25;
所以在行中
x = {1,2,3,;5,6,7}
它跟在 3,
之后的有效语句 Array Row Separator 之后。之后需要一个新语句,在本例中是双 5。有效。
现在考虑这种情况
x = {1,2,3,;;;;4,5,6;;;}
如上 3 之后,
跟在语句 Array Row Separator 之后,大概 可能 null statement - NOP借用一些用 C 编写的底层程序核心,这基本上意味着:什么都不做。所以在 3,;
之后跟随着三次 "do nothing",然后才出现下一个语句。 没有意义,正如 Matlab 告诉您的那样:多余的分号是不必要的。 - 但有效。
它还允许你做一些毫无意义的事情,比如:
if true
;
end
这大概也是
的原因C = {1,2,3,,,}
返回错误,因为逗号 ,
不是 null 语句,但在第一个逗号之后应该有一个语句。
底线:它看起来很奇怪,但实际上对我来说似乎是合乎逻辑的,因为 Matlab 在内部使用了大量 C 代码并考虑到 null 语句,所有提到的都是有效语法。
其他语言呢?
在 Python 中,像 x = [1,2,3,;;;;4,5,6;;;]
这样使用的分号是无效的,即使在预期的 Matlab 克隆中也是如此 numpy,除非包含在这种不常见的语法中 a = np.matrix('1,2,3;4,5,6')
。
a = np.matrix('1,2,3,;;;;4,5,6;;;')
也会引发错误,因为 ;
在任何情况下都被解释为 Array Row Separator,这会使编译器提示行大小不一致。
但是,
x = [1,2,3,]
在 Python
和 IronPython
中也是有效的语法,就像在 VBScript
和 Lua
中提到的一样mlepage's answer .所有这些语言有什么共同点?它们都是(或多或少)在运行时解释的脚本语言。不仅仅是 Matlab。因此,OP 的兴奋仍然没有理由。
关于arrays - 为什么元胞数组中的尾随逗号是有效的 Matlab 语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32849720/