-1

How would I go about creating the matrix

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

using the numpy.diag() function in Python?

I want to define the main diagonal and also the parallel diagonals of the matrix.

Jesper
  • 1,611
  • 13
  • 10

1 Answers1

1

This should do it:

import numpy as np

subdiagonal = np.diag([-1,-1,-1,-1], -1)
diagonal = np.diag([1,1,1,1,1])
superdiagonal = np.diag([2,2,2,2], 1)

total = subdiagonal + diagonal + superdiagonal

print(total)

It gives this output:

[[ 1  2  0  0  0]
 [-1  1  2  0  0]
 [ 0 -1  1  2  0]
 [ 0  0 -1  1  2]
 [ 0  0  0 -1  1]]
Jesper
  • 1,611
  • 13
  • 10