从展平索引获取矩阵的坐标
我们如何从维度矩阵的形状和展平索引获得维度矩阵的坐标?
我的意思是,例如,如果我有以下二维 (2,3) 矩阵:
[ [ 0, 1 ],
[ 2, 3 ],
[ *4*, 5 ] ]
...并且我想从坐标 [0,2] 中找到粗体索引的值,我该怎么办?
或者,如果我有这个 3 维 (2,2,5) 矩阵:
[ [ [ nil, nil ],
[ nil, nil ] ],
[ [ nil, nil ],
[ nil, nil ] ],
[ [ nil, *9* ],
[ nil, nil ] ],
[ [ nil, nil ],
[ nil, nil ] ],
[ [ nil, nil ],
[ nil, nil ] ] ]
...并且我知道我想要的坐标的展平索引值为 9,我如何找到相对坐标为:[1,0, 2]?
如果可能的话,我想知道一种通用且简单的方法,适用于任何形状的矩阵。
非常感谢您的帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用这个简单的算法:
假设您有矩阵 A[a][b][c][d] (其中 a、b、c、d 是维度)和索引 X。
要获取索引 X 只需将 X 除以 b*c*d 即可。
让它成为下一个矩阵,大小为 [2][5] 且索引 X=7
您首先将 X 除以最后一个维度以找到第一个坐标。 X/5=1 。然后,从那里继续前进并为 X 赋予值 X%=5 。所以你会有 X = 7%5 =2。现在您必须使用相同的算法搜索其余维度的坐标。如果到达最后一个维度,坐标将是剩余的 X,在本例中为 2。因此 X=7 的坐标是 [1][2] ,这实际上是答案。
同样,对于一般情况,您有 a、b、c、d 尺寸。
我将用 (yd) 标注第 y 维。
如果您的尺寸为 [2][2][5] 您将得到:
要从 [0][1][4] 到索引 9 ,您可以通过乘法执行相反的算法:
X=(1d )*b*c + (2d)*c + 3d = 0 + 1*5 +4 =9
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
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.
If you had the dimensions [2][2][5] you would get:
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