Make special diagonal matrix in Numpy

前端 未结 5 1321
时光取名叫无心
时光取名叫无心 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:50

    Using my answer to this question: changing the values of the diagonal of a matrix in numpy , you can do some tricky slicing to get a view of each diagonal, then do the assignment. In this case it would just be:

    import numpy as np
    A = np.zeros((4,6))
    # main diagonal
    A.flat[:A.shape[1]**2:A.shape[1]+1] = a
    # first superdiagonal
    A.flat[1:max(0,A.shape[1]-1)*A.shape[1]:A.shape[1]+1] = b
    # second superdiagonal
    A.flat[2:max(0,A.shape[1]-2)*A.shape[1]:A.shape[1]+1] = c
    

提交回复
热议问题