如何在Python中实现Matlab风格的布尔索引删除矩阵行?
Hey there! Let's walk through how to replicate that MATLAB operation in Python using SciPy's sparse matrices. The key adjustments we need to make are for Python's 0-indexing and matching MATLAB's column-major flattening of the boolean matrix.
Here's the step-by-step code with explanations:
First, import the necessary libraries:
import numpy as np from scipy import sparse
Create your 9×9 sparse identity matrix. We'll use CSR format here because it’s optimized for efficient row operations:
var1 = sparse.eye(9, format='csr')
Next, build the 3×3 boolean matrix, mirroring your MATLAB modifications but using 0-indexed indices:
bol = np.zeros((3, 3), dtype=bool) bol[2:, :] = True # Sets the 3rd row (MATLAB's 3:3) to True bol[:, :1] = True # Sets the 1st column (MATLAB's 1:1) to True bol[:1, :] = True # Sets the 1st row (MATLAB's 1:1) to True bol[:, 2:] = True # Sets the 3rd column (MATLAB's 3:3) to True
Now, flatten the boolean matrix in column-major order—this matches how MATLAB's bol(:) flattens the matrix (column-wise instead of Python's default row-wise):
bol_flat = bol.flatten(order='F')
Finally, keep only the rows where the flattened boolean vector is False (since we want to delete rows where it’s True). In Python, we use the ~ operator to negate the boolean mask:
var1 = var1[~bol_flat, :]
If you print var1, you’ll see it’s a 1×9 sparse matrix with a single entry at (0, 4)—this is equivalent to MATLAB’s (1,5) result because Python uses 0-indexing.
A quick note: Using CSR format is crucial here because it supports efficient row slicing. If you create the sparse matrix in another format (like COO), you’d need to convert it to CSR first with .tocsr() before performing the row indexing.
内容的提问来源于stack exchange,提问作者Dimitri Harder

