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

Barbara Streisand
Release: 2024-10-21 14:15:02
Original
460 people have browsed it

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

Rolling Matrix Rows Independently using Advanced Indexing

Given a matrix A and an array r containing roll values for each row, your goal is to roll each row of A independently using those roll values.

The most efficient approach to achieve this is through advanced indexing in NumPy. This technique involves constructing a new meshgrid that applies the roll values to the columns of A. Here's how you can implement it:

<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>
Copy after login

This approach uses negative shifted column indices to ensure valid indexing and applies the roll values through the meshgrid, resulting in a matrix with independently rolled rows.

The above is the detailed content of How to Perform Independent Rolling of Matrix Rows Using Advanced Indexing in NumPy?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template