Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB 2013a: sum + squeeze dimension inconsistencies

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!

like image 678
John Smith Avatar asked Oct 21 '15 06:10

John Smith


2 Answers

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
like image 58
Luis Mendo Avatar answered Nov 15 '22 06:11

Luis Mendo


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
like image 26
rst Avatar answered Nov 15 '22 07:11

rst