4

I'm trying to fill the off diagonal elements on a 100x100 matrix, as shown below in the matlab code, so how to duplicate it in python.

T=(2*t0*diag(ones(1,100)))-(t0*diag(ones(1,99),1))-(t0*diag(ones(1,99),-1))

So I know that the first terms of RHS will fill the diagonal of the matrix with the value 2*t0,

which I do in python as follows:

x = np.zeros((100,100))
np.fill_diagonal(x,2*t0)

but I don't know how to do the 2nd and the 3rd terms, I know that they will fill the values above and below the diagonal elements with value of -t0, not all the off diagonal values but only filling the upper and lower value of diagonal with -t0, rest all are zeros, but I don't know how to write the python code for it.

I found this code:

# diagonal with offset from the main diagonal
diag([1,2,3], k=1) 

will give output as:

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

but how to apply it for a large matrix as in the case of my problem? I work in interactive python i.e. Anaconda, so which are the other packages that I can use for my problem?

Kraay89
  • 919
  • 1
  • 7
  • 19
Cliff
  • 53
  • 1
  • 1
  • 6
  • 5
    In the future (`numpy version 1.10`), you will be able to do this really easily with [`numpy.diagonal`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.diagonal.html#numpy.diagonal). Unfortunately, the future isn't here yet ... – mgilson Dec 18 '13 at 07:05
  • 1
    Future is [here](https://stackoverflow.com/a/35022497/1150462) now – xuhdev Feb 08 '18 at 23:22

2 Answers2

10

From what you supply here np.diag, it is easy to do:

a = np.ones((1, 100))[0]
b = np.ones((1, 99))[0]
m = np.diag(a, 0) + np.diag(b, -1) + np.diag(b, 1)

m here is the 100x100 tridiagonal matrix

Update:

I found a link here on a similar problem, have a look as well.

Community
  • 1
  • 1
Ray
  • 2,472
  • 18
  • 22
  • @user3048426 You are welcome. If this is exactly what you are looking for, consider accepting my answer. :) – Ray Dec 18 '13 at 07:39
1

Try np.triu() and np.tril()

numpy.tril(m, k=0)

  Lower triangle of an array.
  Return a copy of an array with elements above the k-th diagonal zeroed.
  Parameters: m - array_like, shape (M, N), input array; k - int, optional

  Diagonal above which to zero elements. k = 0 (the default) is the main diagonal, k < 0 is below it and k > 0 is above.


 numpy.triu(m, k=0)

 Upper triangle of an array.
 Return a copy of a matrix with the elements below the k-th diagonal zeroed.

Example with a 3x3 matrix:

a=np.array([1,2,3,4,5,6,7,8,9]).reshape(3,3)
print(a)
>>> array([[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]])

a_diag=np.tril(np.triu(a, k=0), k=0)
print (a_diag)

>>> array([[1, 0, 0],
          [0, 5, 0],
          [0, 0, 9]])
Perfect Square
  • 1,368
  • 16
  • 27
maleckicoa
  • 481
  • 5
  • 8