pythonarraysnumpymatrixtoeplitz

Make special diagonal matrix in 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?


Solution

  • This is an example of a Toeplitz matrix - you can construct it using scipy.linalg.toeplitz:

    import numpy as np
    from scipy.linalg import toeplitz
    
    first_row = np.array([1, 2, 3, 0, 0, 0])
    first_col = np.array([1, 0, 0, 0])
    
    print(toeplitz(first_col, first_row))
    # [[1 2 3 0 0 0]
    #  [0 1 2 3 0 0]
    #  [0 0 1 2 3 0]
    #  [0 0 0 1 2 3]]