The following observations are key here:
- The inconsistency you mention is buried deep into the Matlab language: all arrays are considered to be at least 2D. For example,
ndims(pi)
gives 2
.
- Another rule in Matlab is that all arrays are assumed to have infinitely many trailing singleton dimensions. For example,
size(pi,5)
gives 1
.
According to observation 1, squeeze
won't remove singleton dimensions if doing so would give less than two dimensions. This is mentioned in the documentation:
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
.
If you want to get rid of the first singleton, you can exploit observation 2 and use 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)
gives
ans =
20 1
ans =
20 2