I have a different view than yours. You said:
I know this (considering a as 1-D array) solution works but it is a mess and very hard to implement when each dimension has a different size (and you don't even know the number of dimensions)
I think otherwise. Let me show you.
MATLAB is column-major i.e. if you tell MATLAB to collapse a n-D matrix into a 1-D vector, it would do the following steps:
- Take the first dimension.
- Take the first column, append second column to it, then third column etc. This way, it collapses the first dimension.
- Then take the next dimension, repeat the second step and append the obtained vector to the current vector. (Till you finish up all the dimensions).
Take this for example:
a=randi(12,2,2,2,2)
a(:,:,1,1) =
7 8
10 5
a(:,:,2,1) =
4 6
6 5
a(:,:,1,2) =
7 6
9 6
a(:,:,2,2) =
2 4
1 4
Collpase the matrix a
.
b=a(:)
b =
7
10
8
5
4
6
6
5
7
9
6
6
2
1
4
4
Now once you understand the collapsing procedure, it is straightforward to build a general formula. Lets say you want to access the outermost dimension 1
(exactly as in the question).
dimToAccess=1;
sz=size(a);
c=b(prod(sz(1:end-1))*(dimToAccess-1)+1:prod(sz(1:end-1))*(dimToAccess));
Lets test it.
a=randi(12,2,2,2,2)
a(:,:,1,1) =
7 8
10 5
a(:,:,2,1) =
4 6
6 5
a(:,:,1,2) =
7 6
9 6
a(:,:,2,2) =
2 4
1 4
b=a(:);
dimToAccess=1;
sz=size(a);
c=b(prod(sz(1:end-1))*(dimToAccess-1)+1:prod(sz(1:end-1))*(dimToAccess));
%Test - It should produce 1 as output.
isequal(reshape(c,[size(a,1) size(a,2) size(a,3)]),a(:,:,:,dimToAccess))
Answer seems long but its really of 4 lines.