下numpy的对角线创建元素的数组矩阵 [英] create a matrix from array of elements under diagonal in numpy

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

问题描述

我想创建一个使用它的元素是矩阵下的对角线元素的列表的矩阵。

I would like to create a matrix using a list whose elements would be the elements of the matrix under the diagonal.

import numpy as np
x1 = np.array([0.9375, 0.75, 0.4375, 0.0, 0.9375, 0.75, 0.4375, 0.9375, 0.75, 0.9375])
x1

我想有矩阵是

array([[ 1.    ,  0.9375,  0.75  ,  0.4375,  0.    ],
   [ 0.9375,  1.    ,  0.9375,  0.75  ,  0.4375],
   [ 0.75  ,  0.9375,  1.    ,  0.9375,  0.75  ],
   [ 0.4375,  0.75  ,  0.9375,  1.    ,  0.9375],
   [ 0.    ,  0.4375,  0.75  ,  0.9375,  1.    ]])

我想你可以和这样做的 np.tril ,但它给出了一个结果,我不期望。

I thought you could do this with np.tril but it gives a result I do not expect.

mat = np.tril(x1, k = -1  )
print(mat)

我缺少什么?

我提前道歉,如果这是一个微不足道的问题,但我无法弄清楚如何将它不用循环。

I apologize in advance if this is a trivial question but I could not figure out how to it without looping.

推荐答案

您可以这样做:

x = np.ones((5, 5), dtype=float)
x[np.triu_indices(5, 1)] = x1        # sets the upper triangle
x[np.triu_indices(5, 1)[::-1]] = x1  # sets the lower triangle 

在最后一行时,指数,因​​为你的 X1逆转是有序的上三角。你也可以使用 X [np.tril_indices(5 -1)= X1 [:: - 1]。如果感觉更直观

In the last line, the indices are reversed since your x1 is ordered for the upper triangle. You could also use x[np.tril_indices(5, -1)] = x1[::-1] if that feels more intuitive.

这篇关于下numpy的对角线创建元素的数组矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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