MATLAB: Avoid squeeze of a matrix??

squeeze

Hi to all,
I face a problem with the handling of a 12 D matrix in matlab and I do not know if there is any more elegant solution… In particular, let's say that I have a matrix called "A" which is a 12D matrix and the size of this matrix is:
size(A)= 4096 1 1 8 1 1 1 1 1 1 1 124
For some reason I want to create a similar matrix called "B" with the last dim be the sum of the 124 elements of matrix A, B=sum(A,12) the problem then is that matlab squeezes the other dimensions which are equal to 1… so
size(B)= 4096 1 1 8
For the purposes of my application I want this matrix to be a 12D since this matrix is used by one other script and assumes that B is a 12D.
The solution that I found is
newSize =size(A)
newSize(12) =2
B= zeros (newSize)
and so on…
It works but it's really silly to have one additional dimension which is completely 0 and not be able to keep the 12Dim format of matrix B. Is there any other way to address this problem??
Thank you in advance for your suggestions guys.

Best Answer

Matlab's convention is to not show trailing singleton dimensions, but that doesn't mean they don't exist (this is different from squeeze, which actually permutes the dimensions of the matrix).
In your case, you can still work with B as it is; any operations that require those trailing dimensions still work. For example:
a = rand(2, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2);
b = sum(a, 12);
c = cat(12, a, b);
>> size(a)
ans =
2 1 1 2 1 1 1 1 1 1 1 2
>> size(b)
ans =
2 1 1 2
>> size(c)
ans =
2 1 1 2 1 1 1 1 1 1 1 3