查找在Python中矩阵变为单数的值

2024-06-08 20:52:29 发布

您现在位置:Python中文网/ 问答频道 /正文

让我们以下面的平方矩阵为例:

import numpy as np
A = np.array([[10.0, -498.0],
             [-2.0, 100.0]])

如果A的行列式(A[0,0]*A[1,1]-A[0,1]*A[1,0])为零,则A为单数。例如,如果[0,1]的值为-500.0(所有其他值不变),则A将为单数:

from sympy import symbols, Eq, solve

y = symbols('y')
eq = Eq(A[0,0]*A[1,1]-y*A[1,0])
sol = solve(eq)
sol

如何有效地找到A(或任何给定的方阵)变得奇异的所有值(A[0,0],[0,1],…)(我处理大型矩阵)?非常感谢


Tags: fromimportnumpyasnp矩阵arrayeq
2条回答

这东西适用于方阵

它所做的是强行遍历矩阵中的每一项,并检查其是否为单数(因此有许多混乱的输出,如果您喜欢,请使用它)

同样重要的是,它是一个递归函数,如果矩阵是奇异的,它会返回一个矩阵。所以它会递归地抛出递归错误

这是我想出的代码,如果你觉得合适的话,你可以使用它

import numpy as np

def is_singular(_temp_int:str, matrix_size:int):
  kwargs = [int(i) for i in _temp_int]

  arr = [] # Creates the matrix from the given size
  temp_count = 0
  for i in range(matrix_size):
    arr.append([])
    m = arr[i]
    for j in range(matrix_size):
      m.append(int(_temp_int[temp_count]))
      temp_count += 1

  n_array = np.array(arr)
  if int(np.linalg.det(n_array)) == 0:
    print(n_array) # print(n_array) for a pretty output or print(arr) for single line output of the determinant matrix
  _temp_int = str(_temp_int[:-len(str(int(_temp_int)+1))] + str(int(_temp_int)+1))
  is_singular(_temp_int, matrix_size)

# Only square matrices, so only one-digit integer as input
print("List of singular matrices in the size of '3x3': ")
is_singular('112278011', 3)
# Just give a temporary integer string which will be converted to matrix like [[1, 1, 2], [2, 7, 8], [0, 1, 1]]
# From the provided integer string, it adds up 1 after every iteration

我想这就是你想要的代码,如果不起作用,请告诉我

诀窍是使用拉普拉斯展开来计算行列式。公式是

det(A) = sum (-1)^(i+j) * a_ij * M_ij

因此,要使矩阵奇异,只需使用上述公式,将主题更改为a_ij,并设置det(a)=0。可以这样做:

import numpy as np

def cofactor(A, i, j):
    A = np.delete(A, (i), axis=0)
    A = np.delete(A, (j), axis=1)
    return (-1)**(i+j) * np.linalg.det(A)


def make_singular(A, I, J):
    n = A.shape[0]
    s = 0
    for i in range(n):
        if i != J:
            s += A[I, i] * cofactor(A, I, i)

    M = cofactor(A, I, J)
    if M == 0:
        return 'No solution'
    else:
        return -s / M

测试:

>>> M = np.array([[10.0, -498.0],
                  [-2.0, 100.0]])
>>> make_singular(M, 0, 1)
-500.0000000000002

>>> M = np.array([[10.0, -498.0],
                  [0, 100.0]])
>>> make_singular(M, 0, 1)
'No solution'

相关问题 更多 >