开发者

Get the coordinates of a matrix from its flatten index

How can we get the coordinates of a n dimensions matrix from its shape and its flatten index?

I mean, if for example I have the following (2,3) matrix of 2 dimensions:

[ [ 0, 1 ], 
  [ 2, 3 ], 
  [ *4*, 5 ] ]

...and I want to find the value of the index in bold from the coordinates [0,2], how can I do?

Or if I have this (2,2,5) matrix of 3 dimensions:

[ [ [ nil, nil ], 
    [ nil, nil ] ], 
  [ [ nil, nil ], 
    [ nil, nil ] ], 
  [ [ nil, *9*   ], 
    [ nil, nil ] ], 
  [ [ nil, nil ], 
    [ nil, nil ] ], 
  [ [ nil, nil ], 
    [ nil, nil ] ] ]

...and I know the coordinates that I want have a flatten index value of 9, how can I find the relative coordinates are: [1,0,2]?

If possible, I would like to know a general and simple method, which work on matrix of any 开发者_如何转开发shape.

Many thanks for your help.


You can use this simple algorithm:

Let's say you have the matrix A[a][b][c][d] (where a,b,c,d are the dimensions) and the index X.

To get the first coordinate of the index X you simply divide X by b*c*d.

Let it be this next matrix, having the sizes [2][5] and the index X=7

 0 1 2 3 4
 5 6 7 8 9

You first divide X by the last dimension to find the first coordinate. X/5=1 . Then, from there you move forward and give X the value X%=5 . So you'll have X = 7%5 =2. Now you have to search the coordinates for the remaining dimensions using the same algorithm. If you reach the last dimension , the coordinate will be the remaining X, in this case 2. So the coordinates for X=7 are [1][2] , which is actually the answear.

Again, for the general case, where you have a,b,c,d dimensions.
I'll note with (yd) the y'th dimension.

X=index
(1d)=X/b*c*d
X gets value X % b*c*d

(2d)=X/c*d
X gets value X % c*d

(3d)=X/d
X gets value X % d

(4d)=X

If you had the dimensions [2][2][5] you would get:

X=9;

(1d) = 9/2*5 = 0
X = 9%10 = 9

(2d) = 9/5 = 1
X = 9%5 = 4

(3d) = 4

Result: [0][1][4] is the 9th element.

To get from [0][1][4] to the index 9 , you do the reverse algorithm by multiplying:

X=(1d)*b*c + (2d)*c + 3d = 0 + 1*5 +4 =9

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜