0

I'm trying to learn python. In it, I'm trying to dynamically generate a N x M matrix in python, where each cell contains the index value of that cell in python.

The matrix would look like:
[0,1,2,3,4
 0,1,2,3,4
 ...]

I know that in java it would go something like:

a={}{}

    for (i=0;i<N;i++)
      for (j=0;j<M:j++)
         a[i][j] = i

Where N is the width of the matrix and M is the height of the matrix

Except in python it seems like I can't iterate on a matrix on the basis of the cell placement, rather I need to iterate on the basis of the elements in the cell. From my experience something like

a = [][]
a = np.zeroes((N, M))
[ 0, 0, 0
  0, 0, 0]

in the case where N = 3, and M = 2

and then the same style of a loop:

j = 0
   for i in len(a):
     a[i][j] = i
       if i == len(a):
           j = j+1

doesn't work because python can't iterate on the basis of the places of the elements. Perhaps I am wrong. Would this work? Is there a better way to make such a matrix and fill it with the indexed values?

user3097236
  • 37
  • 1
  • 8
  • 1
    "python can't iterate on the basis of the places of the elements." Are you trying to do `for i in range(len(a)):`? – Kevin Aug 27 '15 at 20:04
  • You asking about `matrix`, but you probably want `numpy.array`, `numpy.matrix` exists but it is not as commonly used as `numpy.array`. http://stackoverflow.com/questions/4151128/what-are-the-differences-between-numpy-arrays-and-matrices-which-one-should-i-u – Akavall Aug 27 '15 at 20:16

4 Answers4

5

Since you're already using NumPy, you could use numpy.arange and numpy.tile:

In [26]: N = 5

In [27]: M = 4

In [28]: np.tile(np.arange(N), (M, 1))
Out[28]: 
array([[0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4],
       [0, 1, 2, 3, 4]])
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

Another option is to create a row using np.arange(5) and assign it to every row of zeros matrix.

In [22]: m = np.zeros((4,5))

In [23]: m[:,] = np.arange(5)

In [24]: m
Out[24]: 
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 0.,  1.,  2.,  3.,  4.],
       [ 0.,  1.,  2.,  3.,  4.],
       [ 0.,  1.,  2.,  3.,  4.]])
Akavall
  • 82,592
  • 51
  • 207
  • 251
0

Some example similar to your Java example, but with python syntax sugar.

>>> N=M=5
>>> for z in [[n for n in xrange(N)] for m in xrange(M)]:
...     print z
... 
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
wWolfovich
  • 41
  • 4
0

Here is the code in which matrix contain index value of that cell:

n,m=map(int,raw_input().split())
a=n*[m*[0]]
j=0
for i in range (0,n):
    for j in range(0,m):
        a[i][j]=j
for i in range (0,n):
    for j in range(0,m):
        print a[i][j],
    print
Rohit-Pandey
  • 2,039
  • 17
  • 24