为什么以下代码将此矩阵识别为非奇异矩阵?

0 投票
0 回答
45 浏览
提问于 2025-04-12 02:41

这是我代码的一部分:

import numpy as np
from copy import copy
from random import randint


# With this matrix it doesn't give an error
matriz_aux = [
[None,    6, None,    9],
[   9, None,    3, None],
[None,    5,    4, None]
]

# With this matrix it gives an error
matriz_aux = [
[5, 6, None, 5, 5],
[None, None, 3, None, None],
[None, None, 0, None, 1]
]
matrix_aux_with_num_decompositions = copy(matriz_aux)

matriz_aux = np.array(matriz_aux)
rows, cols = matriz_aux.shape
seq = np.zeros((rows+cols, rows+cols))
vals = []

# Setup matrix representing system of equations
for i in range(rows):
    for j in range(cols):
        if matriz_aux[i,j]:
            seq[len(vals), i] = 1
            seq[len(vals), rows + j] = 1
            vals.append(matriz_aux[i,j])

# Set arbitrary values so matrix is non-singular
for extra_eq in range(len(vals), rows+cols):
    seq[extra_eq, extra_eq] = 1
    vals.append(randint(0, 100))

try:
    dcmp = np.linalg.solve(seq, vals)
    for row in range(rows):
        matrix_aux_with_num_decompositions[row].append(dcmp[row])
    matrix_aux_with_num_decompositions.append(list(dcmp[rows:]))
except np.linalg.LinAlgError as e:
    print(f"Error {str(e)}: The matrix is singular. The system of linear equations cannot be solved.")

for row in matrix_aux_with_num_decompositions: print(row)

一个正确的输出可能是这样的分解矩阵:

matrix_aux_with_num_decompositions = [
[   5,    6, None,    5,    5,  2],
[None, None,    3, None, None,  1],
[None, None,    0, None,    1, -2],
[   3,    4,    2,    3,    3]
]

为了能把这个问题当作线性方程组来解决,所有已知的元素需要合理分配,这样才能构建出一个有效的线性方程组,避免出现“奇异矩阵”,也就是信息不足,无法解出线性方程组的情况。

在这里,所有不是None的数值都被分解成两个简单的数值,这两个数值可以是正数也可以是负数,这样它们所在的行和列的和就能组成这些数值。接下来,我们按照分解这些不是None的矩阵数值的逻辑,进行数学运算:

ij_number_to_decompose = i_row_value + j_column_value
5 = 2 + 3
6 = 2 + 4
5 = 2 + 3
5 = 2 + 3
3 = 1 + 2
0 = 2 + (-2)
1 = -2 + 3

需要注意的是,0这个值必须被分解成两个大小相等但符号相反的数值;我觉得这个0就是导致我代码逻辑出现问题的原因。

0 个回答

暂无回答

撰写回答