MATLAB 2013a:求和 + 压缩维度不一致

MATLAB 2013a: sum + squeeze dimension inconsistencies

请让我试着举例说明

numel_last_a = 1;
numel_last_b = 2

a = rand(2,20,numel_last_a);
b = rand(2,20,numel_last_b);
size(squeeze(sum(a,1)))
size(squeeze(sum(b,1)))

在这种情况下,输出将是

ans = 1 20
ans = 20 2

这意味着我必须抓住 numel_last_x == 1 的特殊情况来应用转置操作以与后续步骤保持一致。我猜一定有更优雅的解决方案。你们能帮帮我吗?

编辑:抱歉,代码有误!

你可以使用 shiftdim 而不是 squeeze

numel_last_a = 1;
numel_last_b = 2;

a = rand(2,20,numel_last_a);
b = rand(2,20,numel_last_b);
size(shiftdim(sum(a,1)))
size(shiftdim(sum(b,1)))
ans =

    20     1


ans =

    20     2

以下观察结果是关键:

  1. 您提到的不一致问题深埋在 Matlab 语言中:所有数组都被认为是 至少是 2D。例如,ndims(pi) 给出 2.
  2. Matlab 中的另一个规则是假定所有数组都具有 无限多的尾随单维度 。例如,size(pi,5) 给出 1.

根据观察 1,squeeze 不会删除单一维度,如果这样做会得到少于两个维度的话。文档中提到了这一点:

B = squeeze(A) returns an array B with the same elements as A, but with all singleton dimensions removed. A singleton dimension is any dimension for which size(A,dim) = 1. Two-dimensional arrays are unaffected by squeeze; if A is a row or column vector or a scalar (1-by-1) value, then B = A.

如果你想摆脱 first 单例,你可以利用观察 2 并使用 reshape:

numel_last_a = 1;
numel_last_b = 2;
a = rand(2,20,numel_last_a);
b = rand(2,20,numel_last_b);
as = reshape(sum(a,1), size(a,2), size(a,3));
bs = reshape(sum(b,1), size(b,2), size(b,3));
size(as)
size(bs)

给予

ans =
    20     1
ans =
    20     2