使numpy的特殊的对角矩阵 [英] Make special diagonal matrix in Numpy

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

问题描述

我试图做一个numpy的数组,它看起来像这样:

I am trying to make a numpy array that looks like this:

[a b c       ]
[  a b c     ]
[    a b c   ]
[      a b c ] 

因此​​,这涉及到更新主对角线和两条对角线上方

So this involves updating the main diagonal and the two diagonals above it.

什么是这样做的有效途径?

What would be an efficient way of doing this?

推荐答案

您可以使用 np.indices 来得到你的数组的索引,然后分配值,你在哪里想要的。

You can use np.indices to get the indices of your array and then assign the values where you want.

a = np.zeros((5,10))
i,j = np.indices(a.shape)

I,J 是行和列的索引,分别为。

i,j are the line and column indices, respectively.

a[i==j] = 1.
a[i==j-1] = 2.
a[i==j-2] = 3.

将导致:

array([[ 1.,  2.,  3.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  2.,  3.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  1.,  2.,  3.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  2.,  3.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  1.,  2.,  3.,  0.,  0.,  0.]])

这篇关于使numpy的特殊的对角矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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