如何使用numpy从一维数组创建对角矩阵? [英] How can I use numpy to create a diagonal matrix from a 1d array?

查看:2759
本文介绍了如何使用numpy从一维数组创建对角矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将python和numpy一起使用来做线性代数.

I am using Python with numpy to do linear algebra.

我对矩阵执行了numpy SVD,以获得矩阵U,i和V.但是,i矩阵表示为1行的1x4矩阵.即:[ 12.22151125 4.92815942 2.06380839 0.29766152].

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].

如何获取numpy来将i矩阵表示为对角矩阵,如下所示: [[12.22151125, 0, 0, 0],[0,4.92815942, 0, 0],[0,0,2.06380839,0 ],[0,0,0,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]]

我正在使用的代码:

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?

推荐答案

使用numpy的

Use numpy's diag function:

numpy.diag(i)

从文档中:

提取对角线或构造对角线数组.

Extract a diagonal or construct a diagonal array.

这篇关于如何使用numpy从一维数组创建对角矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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