简体   繁体   English

如何在 numpy 中将矩阵变为对角矩阵?

[英]how to make matrix into diagonal matrix in numpy?

given matrix:给定矩阵:

x = matrix([[ 0.9,  0.14], [ 0.15,  0.8]])

how can you make the first column, x[:,0] , into a diagonal matrix in numpy?如何使第一列x[:,0]成为 numpy 中的对角矩阵? to get:要得到:

matrix([[0.9, 0],
        [0, 0.15]])

There is a diagflat that 'Create a two-dimensional array with the flattened input as a diagonal.'. 有一个diagflat ,“用展平的输入作为对角线创建二维数组”。 It both ravels the input, and wraps the result in np.matrix (matching the input array type): 它既ravels输入,也将结果包装在np.matrix (与输入数组类型匹配):

In [122]: np.diagflat(x[:,0])
Out[122]: 
matrix([[ 0.9 ,  0.  ],
        [ 0.  ,  0.15]])

So it's doing all the work of jez answer, just wrapping it in a generalized function: 因此,它完成了jez Answer的所有工作,只是将其包装在通用函数中:

np.matrix(np.diag(np.asarray(x[:,0]).ravel()))
numpy.diag( x.A[ :, 0 ] )

should do it. 应该这样做。

The difference between a matrix and an array is crucial here. matrixarray之间的区别在这里至关重要。 You won't get the same result from just numpy.diag( x[ :, 0 ] ) . 仅从numpy.diag( x[ :, 0 ] )您将不会获得相同的结果。 xA is a shorthand for numpy.asarray( x ) when x is a matrix . xmatrix时, xAnumpy.asarray( x )的简写。

So by the same token, to answer your question precisely I guess I shouldn't forget convert the answer from an array back to a matrix : 因此,出于同样的原因,我想确切地回答您的问题,我想我不应该忘记将答案从array转换回matrix

numpy.matrix( numpy.diag( x.A[ :, 0 ] ) )

You can use np.diag(np.diag(your numpy array)) .您可以使用np.diag(np.diag(your numpy array)) Eg例如

>>> import numpy as np
>>> b = np.arange(1,10).reshape(3,3)
>>> b
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> np.diag(np.diag(b))
array([[1, 0, 0],
       [0, 5, 0],
       [0, 0, 9]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM