Search code examples
pythonnumpymatrixoffsetdiagonal

How to change offset of matrix python numpy


I would like to get a matrix in shape of 100x100 like this:

[-2,1,0,0]
[1,-2,1,0]
[0,1,-2,1]
[0,0,1,-2]

I started with creating the diagonal:

import numpy as np
diagonal= (100)
diagonal= np.full(diagonal, -2)
A100 = (100,100)
A100 = np.zeros(A100)
np.fill_diagonal(A100, diagonal)

Now for changing the offset I tried:

off1=(99)
off1=np.ones(off1)
off1=np.diagonal(A100, offset=1)

But this doesn`t work. Thanks for your help!


Solution

  • Construct the matrix from three identity matrices:

    np.eye(100, k=1) + np.eye(100, k=-1) - 2 * np.eye(100)
    

    P.S. This solution is 7x faster than the scipy.sparse solution.