问题
Say I have a 3x4x5x6 java double array a
that I unroll into an ArrayList b
of length 360 in the following way:
for (int i = 0; i<a.length; i++){
for (int j = 0; j<a[0].length; j++){
for (int k = 0; k<a[0][0].length; k++){
for (int m = 0; m<a[0][0][0].length; m++){
b.add(a[i][j][k][m]);
}
}
}
}
Given the index of b
, is there an easy way to find the corresponding 4-tuple of indices in a
?
回答1:
Assuming that
b
is the index on the monodimensional arrayi,j,k,m
are the four resulting indices on the multidimensional arraysi,sj,sk,sm
are the size of any dimension
you can use basic math, it should be something like
m = b % sm
k = (b / sm) % sk
j = (b / (sm*sk)) % sj
i = b / (sm*sk*sj)
Basically you increment every index by one for every size of the contained arrays (by multiplying sizes) and you wrap it on its dimension.
回答2:
In MATLAB you can use ind2sub to convert linear indices to subscripts.
Eg. a 4-dimensional (3 x 3 x 3 x 3) matrix:
#% The dimensions of n-dimensional matrix:
SizeVector = [ 3, 3, 3, 3 ];
#% Example linear index:
LinearIndex = 17;
[i1, i2, i3, i4 ] = ind2sub(SizeVector, LinearIndex);
i1 =
2
i2 =
3
i3 =
2
i4 =
1
To check this is correct you can compute the original linear address manually from these subscripts:
(i4-1)*3^3 + (i3-1)*3^2 + (i2-1)*3^1 + (i1-1)*3^0 + 1
ans =
17
来源:https://stackoverflow.com/questions/12429492/how-to-convert-a-monodimensional-index-to-corresponding-indices-in-a-multidimens