英文:
How to iterate over indices of a matrix?
问题
在Python中,当我们想要迭代遍历具有任意维度的矩阵时,我们可以使用以下代码行:
for index in np.ndindex(data.shape[2:]):
例如:
> for index in np.ndindex(3, 2, 1):
> print(index) (0, 0, 0) (0, 1, 0) (1, 0, 0) (1, 1, 0) (2, 0, 0) (2, 1, 0)
在Java中,以简单的方式,我们可以使用确定数量的for循环来完成,但前提是了解维度。但在任意维度中,算法必须更复杂。
在ND4J库中是否有用于迭代索引的内置方法?
英文:
In Python when we want to iterate over a matrix with an arbitrary dimension, we can use this line of code:
for index in np.ndindex(data.shape[2:]):
for example :
> for index in np.ndindex(3, 2, 1):
> print(index) (0, 0, 0) (0, 1, 0) (1, 0, 0) (1, 1, 0) (2, 0, 0) (2, 1, 0)
in java, in an easy way, we can do it with a determined number of for loop, but the prerequisite is knowledge about the dimension. But in arbitrary dimensions, the algorithm must be more complicated.
Is there any built-in method in ND4J lib for iterating over indices?
答案1
得分: 2
在 nd4j 中,我们有一个 NDIndexIterator,它允许您迭代遍历坐标。
以下是示例:
NdIndexIterator shapeIter = new NdIndexIterator(2, 2);
//import org.nd4j.linalg.api.iter.NdIndexIterator;
long[][] possibleSolutions = new long[][] {{0, 0}, {0, 1}, {1, 0}, {1, 1},};
for (int i = 0; i < 4; i++) {
assertArrayEquals(possibleSolutions[i], shapeIter.next());
}
英文:
In nd4j, we have a NDIndexIterator that allows you to iterate over the coordinates.
Here is the example:
NdIndexIterator shapeIter = new NdIndexIterator(2, 2);
//import org.nd4j.linalg.api.iter.NdIndexIterator;
long[][] possibleSolutions = new long[][] {{0, 0}, {0, 1}, {1, 0}, {1, 1},};
for (int i = 0; i < 4; i++) {
assertArrayEquals(possibleSolutions[i], shapeIter.next());
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论