如何在numpy中将矩阵变成对角矩阵? [英] how to make matrix into diagonal matrix in numpy?

查看:376
本文介绍了如何在numpy中将矩阵变成对角矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定矩阵:

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

如何将第一列x[:,0]变成numpy中的对角矩阵?得到:

how can you make the first column, x[:,0], into a diagonal matrix in numpy? to get:

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

推荐答案

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

应该这样做.

matrixarray之间的区别在这里至关重要.仅numpy.diag( x[ :, 0 ] )不会获得相同的结果.当xmatrix时,x.Anumpy.asarray( x )的简写.

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.

因此,出于同样的原因,我想确切地回答您的问题,我想我不应该忘记将答案从array转换回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 ] ) )

这篇关于如何在numpy中将矩阵变成对角矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆