Here is a fragment of my code:
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)
A correct output could be this descomposition matrix:
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]
]
In order to be solved as a system of linear equations, all known elements should be distributed so that they can be used to construct a valid system of linear equations, preventing seq from being a singular matrix, that is, a matrix that does not have enough information. to solve the system of linear equations.
Where each of the numerical values that were not None were decomposed into 2 simple numerical values, positive or negative, so that the value of their row and column added together forms them. And following the logic of decomposing those numerical values of the matrix that are not None, in this case these would be the mathematical operations:
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
Note that the value of 0 must necessarily be decomposed into 2 values equal in magnitude but opposite in sign; I believe this 0 is what causes problems in the logic of my code.