Error in Following python program
Peter Otten
__peter__ at web.de
Sat Sep 4 20:49:58 CEST 2010
Pramod wrote:
> #/usr/bin/python
> from numpy import matrix
> n=input('Enter matrix range')
> fr=open('mat.txt','r')
> print ('Enter elements into the matrix\n')
> a=matrix([[input()for j in range(n)] for i in range(n)])
> for i in range(n):
> for j in range(n):
> print a[i][j]
> print '\n'
>
> When i run the above program the following error is Coming please
> Error is
> Enter matrix range3
> Enter elements into the matrix
>
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
> [[1 2 3]]
> Traceback (most recent call last):
> File "2.py", line 10, in <module>
> print a[i][j]
> File "/usr/lib/python2.6/dist-packages/numpy/core/defmatrix.py",
> line 265, in __getitem__
> out = N.ndarray.__getitem__
>
> please resolve my problem Thanks in advance
You can either use an array instead of a matrix and continue to access the
elements like you did in your code
>>> a = numpy.array([[1,2],[3,4]])
>>> a[1][1]
4
or continue to use the matrix and access its elements with a tuple
>>> b = numpy.matrix([[1,2],[3,4]])
>>> b[1,1]
4
If you pass only one index you get another, smaller matrix:
>>> b[1]
matrix([[3, 4]])
Once you see this printed it should be clear that b[1][1] asks for the non-
existent second row of the above matrix. Hence the error:
>>> b[1][1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/dist-packages/numpy/core/defmatrix.py", line 265,
in __getitem__
out = N.ndarray.__getitem__(self, index)
IndexError: index out of bounds
By the way, these matrices are really strange beasts:
>>> b[0][0]
matrix([[1, 2]])
>>> b[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]
matrix([[1, 2]])
Peter
More information about the Python-list
mailing list