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

Barbara Streisand
發布: 2024-10-21 14:15:02
原創
327 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!