MATLAB 2013a: sum + squeeze dimension inconsistencies
Asked Answered
S

2

5

Please let me try to explain by an example

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)))

in this case, the output will be

ans = 1 20
ans = 20 2

This means I have to catch the special case where numel_last_x == 1 to apply a transpose operation for consistency with later steps. I'm guessing that there must be a more elegant solution. Can you guys help me out?

Edit: sorry, code was wrong!

Sanguineous answered 21/10, 2015 at 6:0 Comment(0)
M
6

The following observations are key here:

  1. 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.
  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
Mediatize answered 21/10, 2015 at 9:40 Comment(0)
S
2

You could use shiftdim instead of 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
Satisfactory answered 21/10, 2015 at 7:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.