You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ND4J中反转矩阵列元素?Python转Java实现求助

Reverse Rows (or Column Elements) in ND4J & Convert Python Code to Java

Got it, let's break down how to replicate your Python logic in ND4J and fix the issue with reversing indices.

First, let's clarify what your Python code does: data[index_odd] = tmp[::-1,:] reverses the row order of tmp (so the first row becomes last, last becomes first, etc.) and assigns this reversed subset to specific rows in data.

Why Your Initial interval Approach Didn't Work

ND4J's NDArrayIndex.interval(start, end) expects start <= end to create a forward-moving range—it doesn't handle reverse ranges automatically. To reverse rows (or any dimension), we need a different approach.

Simplest Solution: Use INDArray.reverse()

ND4J has a built-in method to reverse elements along a specific dimension, which is exactly what you need for your Python equivalent:

  • reverse(0) reverses the row order (matches Python's [::-1, :])
  • reverse(1) reverses the column order (matches Python's [:, ::-1])

Here's the direct Java translation of your Python code:

// Reverse the row order of tmp (matches tmp[::-1, :] in Python)
INDArray reversedTmp = tmp.reverse(0);

// Assign the reversed rows to the specified indices in data
data.put(NDArrayIndex.indices(index_odd), reversedTmp);

If You Need to Reverse a Single Column (Not All Rows)

If your goal is to reverse elements in one specific column (e.g., the 2nd column, index 1) instead of all rows, you can target that column specifically:

// Get the column you want to reverse (e.g., column index 1)
INDArray targetColumn = tmp.get(NDArrayIndex.all(), NDArrayIndex.point(1));

// Reverse the column's elements
INDArray reversedColumn = targetColumn.reverse(0);

// Put the reversed column back into the original matrix
tmp.put(NDArrayIndex.all(), NDArrayIndex.point(1), reversedColumn);

Manual Index Construction (Alternative)

If you prefer building the reverse index manually (for more control), you can create an array of reversed row indices and use it with NDArrayIndex.indices():

int rowCount = tmp.rows();
int[] reverseRowIndices = new int[rowCount];

// Populate the array with reversed row numbers (e.g., 9,8,...,0 for 10 rows)
for (int i = 0; i < rowCount; i++) {
    reverseRowIndices[i] = rowCount - 1 - i;
}

// Use the indices to get reversed rows
INDArray reversedTmp = tmp.get(NDArrayIndex.indices(reverseRowIndices), NDArrayIndex.all());

// Assign to data as before
data.put(NDArrayIndex.indices(index_odd), reversedTmp);

All of these approaches will work for your use case—reverse() is the most concise and recommended method for simple dimension reversal.

内容的提问来源于stack exchange,提问作者Amir Shamaee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 22:07:33