0

I have a file with a matrix: let's say matrix.dat and I want to extract the diagonal, subdiagonal and upper diagonal from it, to create a new tridiagonal matrix M. I know that with numpy you can get the diagonal, but is there any way to extract the data of the subdiagonal or upper diagonal.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Jack MR
  • 37
  • 5

1 Answers1

1

You can construct a tridiagonal matrix in general like this.

from scipy.sparse import spdiags
import numpy as np
data = np.array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]])
diags = np.array([0, -1, 1])
array = spdiags(data, diags, 4, 4).toarray()

array([[1, 2, 0, 0],
       [1, 2, 3, 0],
       [0, 2, 3, 4],
       [0, 0, 3, 4]])