首页  >  文章  >  后端开发  >  如何使用 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