how to make matrix into diagonal matrix in numpy?

前端 未结 2 1508
后悔当初
后悔当初 2021-01-22 01:14

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 nump

相关标签:
2条回答
  • 2021-01-22 01:44
    numpy.diag( x.A[ :, 0 ] )
    

    should do it.

    The difference between a matrix and an array is crucial here. You won't get the same result from just numpy.diag( x[ :, 0 ] ). x.A is a shorthand for numpy.asarray( x ) when x is a matrix.

    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:

    numpy.matrix( numpy.diag( x.A[ :, 0 ] ) )
    
    0 讨论(0)
  • 2021-01-22 01:47

    There is a diagflat that 'Create a two-dimensional array with the flattened input as a diagonal.'. It both ravels the input, and wraps the result in np.matrix (matching the input array type):

    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:

    np.matrix(np.diag(np.asarray(x[:,0]).ravel()))
    
    0 讨论(0)
提交回复
热议问题