You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Numpy与线性代数:如何过滤数组同时保留其形状?

问题:提取矩阵子式时保留二维形状

我正在把实现MCA算法作为学习练习,目标是迭代遍历矩阵并逐行逐列“关闭”元素。我写了minors函数生成布尔选择器数组列表,针对3x3矩阵能生成对应的选择器,但使用A[selector]过滤时数组会被扁平化(比如得到[a22, a23, a32, a33]),请问怎么操作能保留数组形状,得到[[a22, a23], [a32, a33]]这样的结果?

附上我的函数代码:

import numpy as np

def minors(A):
    '''Creates a boolean list of selector arrays.

    Positional arguments
    ----------
    A: array-like
        An array or array like representing a matrix

    Returns
    --------
    selectors: list
        A list of boolean arrays corresponding to the selectors
    '''
    A = np.array(A)
    selectors = [] 

    for r, row in enumerate(A):
        for c, coef in enumerate(row):
            selector = np.ones(A.shape, dtype=bool)

            selector[r] = 0
            selector[0:len(row), c] = 0

            selectors.append(selector)

    return selectors 

3x3矩阵的首个选择器示例:

[
[False, False, False], 
[False,  True,  True],
[False,  True,  True]
]

末位选择器示例:

[
[ True,  True, False],
[True,  True, False],
[False, False, False]
]
解决方案

方法1:用索引切片代替布尔掩码

布尔索引A[selector]会自动扁平化结果,因为它仅提取True位置的元素,不保留原结构。更高效直接的方式是生成要保留的行和列索引,通过切片提取子矩阵:

修改minors函数,直接返回保留二维形状的子矩阵列表:

import numpy as np

def minors(A):
    A = np.array(A)
    submatrices = []
    rows, cols = A.shape
    for r in range(rows):
        for c in range(cols):
            # 生成保留行/列的布尔索引
            keep_rows = np.arange(rows) != r
            keep_cols = np.arange(cols) != c
            # 提取子矩阵,保持二维结构
            submatrix = A[keep_rows][:, keep_cols]
            submatrices.append(submatrix)
    return submatrices

调用该函数后,每个元素都是对应位置的子式矩阵,比如3x3矩阵的第一个子式就是[[a22,a23],[a32,a33]]。

方法2:对扁平化结果手动重塑

如果必须沿用现有的布尔选择器,可以在提取后根据原矩阵维度重塑形状。假设原矩阵是n×n,则每个子式是(n-1)×(n-1):

A = np.array([[1,2,3],[4,5,6],[7,8,9]])
selectors = minors(A)
# 处理第一个选择器的结果
flat_result = A[selectors[0]]
reshaped_result = flat_result.reshape(A.shape[0]-1, A.shape[1]-1)

这种方法需要依赖原矩阵的维度信息,灵活性不如方法1。

方法3:通过坐标重构子矩阵

利用np.where获取布尔选择器中True位置的坐标,再按行重新组织元素构造二维数组:

selector = selectors[0]
row_indices, col_indices = np.where(selector)
unique_rows = np.unique(row_indices)
submatrix = np.array([A[r][col_indices[row_indices == r]] for r in unique_rows])

此方法逻辑稍复杂,效率低于切片方式,仅作为替代方案参考。


内容的提问来源于stack exchange,提问作者Thales Alexandre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 17:37:07