首頁  >  文章  >  後端開發  >  如何使用 NumPy 中的高階索引執行矩陣行的獨立捲動?

如何使用 NumPy 中的高階索引執行矩陣行的獨立捲動?

Barbara Streisand
Barbara Streisand原創
2024-10-21 14:15:02328瀏覽

How to Perform Independent Rolling of Matrix Rows Using Advanced Indexing in NumPy?

使用高級索引獨立滾動矩陣行

給定一個矩陣A 和一個包含每行滾動值的數組r,您的目標是使用這些滾動值獨立滾動A 的每一行。

實現此目的的最有效方法是透過 NumPy 中的高級索引。此技術涉及建立一個新的網格網格,將滾動值應用於 A 的列。以下是實現它的方法:

<code class="python">import numpy as np

# Define the matrix A and roll values r
A = np.array([[4, 0, 0],
              [1, 2, 3],
              [0, 0, 5]])
r = np.array([2, 0, -1])

# Create a meshgrid of rows and negative shifted columns
rows, column_indices = np.ogrid[:A.shape[0], :A.shape[1]]
r[r < 0] += A.shape[1]
column_indices = column_indices - r[:, np.newaxis]

# Use advanced indexing to apply the roll values
result = A[rows, column_indices]

# Print the result
print(result)</code>

此方法使用負移位列索引來確保有效索引並應用滾動值通過網格,產生一個具有獨立滾動行的矩陣。

以上是如何使用 NumPy 中的高階索引執行矩陣行的獨立捲動?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn