Home > Blockchain >  matrix python numpy with positif and negative value
matrix python numpy with positif and negative value

Time:05-26

i want to generate a diagonal matrix with size such as nxn

CodePudding user response:

This is a toeplitz matrix, you can use SciPy's linalg.toeplitz to construct such a pattern. You can look at its implementation code here which uses from np.lib.stride_tricks.as_strided under the hood.

>>> toeplitz(-np.arange(3), np.arange(3))
array([[ 0,  1,  2],
       [-1,  0,  1],
       [-2, -1,  0]])

>>> toeplitz(-np.arange(6), np.arange(6))
array([[ 0,  1,  2,  3,  4,  5],
       [-1,  0,  1,  2,  3,  4],
       [-2, -1,  0,  1,  2,  3],
       [-3, -2, -1,  0,  1,  2],
       [-4, -3, -2, -1,  0,  1],
       [-5, -4, -3, -2, -1,  0]])

CodePudding user response:

It's quite easy to write as a custom function:

def diagonal(N):
    a = np.arange(N)
    return a-a[:,None]

diagonal(3)
array([[ 0,  1,  2],
       [-1,  0,  1],
       [-2, -1,  0]])

diagonal(6)
array([[ 0,  1,  2,  3,  4,  5],
       [-1,  0,  1,  2,  3,  4],
       [-2, -1,  0,  1,  2,  3],
       [-3, -2, -1,  0,  1,  2],
       [-4, -3, -2, -1,  0,  1],
       [-5, -4, -3, -2, -1,  0]])
  • Related