MATLAB中[]和[1x0]之间的差异

Ame*_*ina 22 matlab matrix

我在MATLAB中有一个循环,用我的工作区(2011b,Windows 7,64位)填充单元格数组,其中包含以下条目:

my_array = 
    [1x219 uint16]
    [         138]
    [1x0   uint16] <---- row #3
    [1x2   uint16]
    [1x0   uint16]
    []             <---- row #6
    [         210]
    [1x7   uint16]
    [1x0   uint16]
    [1x4   uint16]
    [1x0   uint16]
    [         280]
    []
    []
    [         293]
    [         295]
    [1x2   uint16]
    [         298]
    [1x0   uint16]
    [1x8   uint16]
    [1x5   uint16]
Run Code Online (Sandbox Code Playgroud)

请注意,某些条目保留[],如行#6,而其他[1x0]条目保存项目,如行#3.

  1. 它们之间有什么区别吗?(除了MATLAB以不同方式显示它们的事实).MATLAB在内存中如何表示它们的差异?
  2. 如果区别仅在于MATLAB内部如何表示它们,为什么程序员应该意识到这种差异呢?(即为什么以不同的方式显示它们?).它是一个(无害的)bug吗?或是否有任何好处在明知这样的阵列被表示不同?

gno*_*ice 21

大多数情况下(例外情况见下文)没有真正的区别.两者都被认为是"空的",因为至少有一个维度的大小为0.但是,我不会称之为错误,因为作为程序员,您可能希望在某些情况下看到此信息.

比如说,你有一个二维矩阵,你想索引一些行和一些列,以提取到一个较小的矩阵:

>> M = magic(4)  %# Create a 4-by-4 matrix

M =
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

>> rowIndex = [1 3];  %# A set of row indices
>> columnIndex = [];  %# A set of column indices, which happen to be empty
>> subM = M(rowIndex,columnIndex)

subM =
   Empty matrix: 2-by-0
Run Code Online (Sandbox Code Playgroud)

请注意,空结果仍会告诉您一些信息,特别是您尝试从原始矩阵索引2行.如果结果刚刚显示[],您将不知道它是否为空,因为您的行索引为空,或者您的列索引为空,或两者都是.

警告......

在某些情况下,定义为空矩阵[](即其所有维度均为0)可能会给出与仍具有某些非零维度的空矩阵不同的结果.例如,矩阵乘法在处理不同类型的空矩阵时可以给出不同的(有些非直观的)结果.让我们考虑这3个空矩阵:

>> a = zeros(1,0);  %# A 1-by-0 empty matrix
>> b = zeros(0,1);  %# A 0-by-1 empty matrix
>> c = [];          %# A 0-by-0 empty matrix
Run Code Online (Sandbox Code Playgroud)

现在,让我们尝试以不同的方式将它们相乘:

>> b*a

ans =
     []  %# We get a 0-by-0 empty matrix. OK, makes sense.

>> a*b

ans =
     0   %# We get a 1-by-1 matrix of zeroes! Wah?!

>> a*c

ans =
   Empty matrix: 1-by-0  %# We get back the same empty matrix as a.

>> c*b

ans =
   Empty matrix: 0-by-1  %# We get back the same empty matrix as b.

>> b*c
??? Error using ==> mtimes
Inner matrix dimensions must agree.  %# The second dimension of the first
                                     %#   argument has to match the first
                                     %#   dimension of the second argument
                                     %#   when multiplying matrices.
Run Code Online (Sandbox Code Playgroud)

通过乘以两个空矩阵来获得非空矩阵可能足以让你的头受伤,但它有点意义,因为结果仍然不包含任何东西(即它的值为0).

  • +1实际上所有这些情况都有意义(至少对我来说).矩阵乘法的定义仍然适用:`m×p`矩阵与'p×n`矩阵的乘积是`m×n`矩阵 (3认同)

Ben*_*igt 6

连接矩阵时,公共维度必须匹配.

如果当其中一个操作数为空时它不匹配,则当前不是错误,但是您确实得到了一个令人讨厌的警告,即未来版本可能更严格.

例子:

>> [ones(1,2);zeros(0,9)]
Warning: Concatenation involves an empty array with an incorrect number of columns.
This may not be allowed in a future release. 
ans =
     1     1

>> [ones(2,1),zeros(9,0)]
Warning: Concatenation involves an empty array with an incorrect number of rows.
This may not be allowed in a future release. 
ans =
     1
     1
Run Code Online (Sandbox Code Playgroud)