0

I have the following code where I have been trying to create a tridiagonal matrix x using if-conditions.

#!/usr/bin/env python

# import useful modules
import numpy as np


N=5
x=np.identity(N)
#x=np.zeros((N,N))
print x

# Construct NxN matrix 
for i in range(N):
     for j in range(N):
        if i-j==1:
            x[i][j]=1 
        elif j-1==1:
            x[i][j]=-1
        else:
            x[i][j]=0

            print "i= ",i," j= ",j          


print x

I desire to get

[[ 0.  -1. 0.  0.  0.]
 [ 1.  0. -1.  0.  0.]
 [ 0.  1.  0.  -1  0.]
 [ 0.  0.  1.  0.  -1.]
 [ 0.  0.  0.  1.  0.]]

However, I obtain

[[ 0.  0. -1.  0.  0.]
 [ 1.  0. -1.  0.  0.]
 [ 0.  1. -1.  0.  0.]
 [ 0.  0.  1.  0.  0.]
 [ 0.  0. -1.  1.  0.]]

What's going wrong?

Bonus question : Can I forcefully index from 1 to 5 instead of 0 to 4 in this example, or Python never allows that?

hbaromega
  • 2,317
  • 2
  • 24
  • 32

2 Answers2

1

elif j-1==1: should be elif j-i==1:.

And no, lists/arrays etc. are always indexed from 0.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
1

As for the bonus question, the first element of a sequence in Python has always the index 0. However, if for some particular reason (for example to prevent off-by-one errors) you wish to count the elements of a sequence from a value other than 0, you could use the built-in function enumerate() and set the value of the optional parameter start to fit your needs:

>>> seq = ['a', 'b', 'c']
>>> for count, item in enumerate(seq, start=1):
...     print(count, item)
...
1 a
2 b
3 c
Tonechas
  • 13,398
  • 16
  • 46
  • 80