在 Python 中对矩阵进行对角化时保持对角线元素的顺序

问题描述 投票:0回答:1

我有一个非对角矩阵,但非对角元素比对角元素小得多,所以在对角化时,我预计对角元素会改变,但只是一点点。我目前只是使用

numpy.linalg.eig
来获取特征值,但是我希望这些值的顺序与对角化之前的(相似)值相同。因此,如果原始矩阵中的对角线是(100,200,300),对角化后我希望输出(101,202,303)而不是(202,303,101)。我需要这个来跟踪对角化后哪个值映射到哪个值。我怎样才能做到这一点?
numpy.linalg.eig
的输出好像没有明确的顺序?谢谢!

python matrix diagonal
1个回答
0
投票

当您使用

numpy.linalg.eig
计算矩阵的特征值时,返回的特征值不一定以任何特定方式排序。可以参考numpy手册https://numpy.org/doc/stable/reference/ generated/numpy.linalg.eig.html

现在为了解决这个问题,我们可以采用一个示例矩阵,其中非对角线元素非零但很小,然后尝试将它们映射到原始顺序

example_matrix = np.array([[100, 0.2, 0.3], [0.2, 200, 0.5], [0.3, 0.5, 300]])

# Compute eigenvalues and eigenvectors
eigenvalues, eigenvectors = np.linalg.eig(example_matrix)

# Original diagonal elements
original_diagonal = np.diag(example_matrix)

# Sort eigenvalues by how close they are to the original diagonal elements
sorted_indices = np.argsort(np.abs(eigenvalues - original_diagonal))

# Sorted eigenvalues and eigenvectors
sorted_eigenvalues = eigenvalues[sorted_indices]
sorted_eigenvectors = eigenvectors[:, sorted_indices]

# Output the sorted eigenvalues and their corresponding eigenvectors
sorted_eigenvalues, sorted_eigenvectors

结果

(array([ 99.99915299, 199.99789408, 300.00295293]),
 array([[-0.9999969 , -0.001985  ,  0.00150496],
        [ 0.0019925 , -0.9999855 ,  0.00500279],
        [ 0.00149501,  0.00500578,  0.99998635]]))

基本上,您需要根据与原始对角线的接近程度对特征值及其相应的特征向量进行排序。通过这种方式,您可以跟踪对特征值进行排序的排列,以便将它们映射回原始顺序。

© www.soinside.com 2019 - 2024. All rights reserved.