如何迭代遍历矩阵的索引?

huangapple go评论80阅读模式
英文:

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 &lt; 4; i++) {
    assertArrayEquals(possibleSolutions[i], shapeIter.next());
}

huangapple
  • 本文由 发表于 2020年8月21日 16:48:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63519566.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定