python 生成对角矩阵,如何使用numpy从一维数组创建对角矩阵?

I am using Python with numpy to do linear algebra.

I performed numpy SVD on a matrix to get the matrices U,i, and V. However the i matrix is expressed as a 1x4 matrix with 1 row. i.e.: [ 12.22151125 4.92815942 2.06380839 0.29766152].

How can I get numpy to express the i matrix as a diagonal matrix like so:

[[12.22151125, 0, 0, 0],[0,4.92815942, 0, 0],[0,0,2.06380839,0 ],[0,0,0,0.29766152]]

Code I am using:

A = np.matrix([[3, 4, 3, 1],[1,3,2,6],[2,4,1,5],[3,3,5,2]])

U, i, V = np.linalg.svd(A,full_matrices=True)

So I want i to be a full diagonal matrix. How an I do this?

解决方案

Use numpy's diag function:

numpy.diag(i)

From the documentation:

Extract a diagonal or construct a diagonal array.

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值