问题描述
在Python中,当我们想遍历具有任意维度的矩阵时,可以使用以下代码行:
for index in np.ndindex(data.shape[2:]):
例如:
> for index in np.ndindex(3,2,1):
> print(index) (0,0) (0,1,0) (1,0) (2,0)
在Java中,可以通过一种简单的方式使用确定数量的for循环来完成,但是前提是必须了解有关维的知识。但是在任意维度上,算法必须更加复杂。
ND4J lib中是否有用于迭代索引的内置方法?
解决方法
在nd4j中,我们有一个NDIndexIterator,可让您遍历坐标。
这里是示例:
NdIndexIterator shapeIter = new NdIndexIterator(2,2);
//import org.nd4j.linalg.api.iter.NdIndexIterator;
long[][] possibleSolutions = new long[][] {{0,0},{0,1},{1,};
for (int i = 0; i < 4; i++) {
assertArrayEquals(possibleSolutions[i],shapeIter.next());
}