Make special diagonal matrix in Numpy

前端 未结 5 1331
时光取名叫无心
时光取名叫无心 2020-12-06 01:09

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 updat

5条回答
  •  生来不讨喜
    2020-12-06 01:48

    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 are the line and column indices, respectively.

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

    will result in:

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

提交回复
热议问题