user31264
user31264

Reputation: 6727

What are the numpy equivalents of R's row() and col() functions?

How to create arrays

0 0 ... 0
1 1 ... 1
...
N N ... N

and

0 1 ... M
0 1 ... M
...
0 1 ... M

The best I can do is:

a = np.tile(np.arange(N+1),(M+1,1)).T
b = np.tile(np.arange(M+1),(N+1,1))

Is there a better solution?

Upvotes: 0

Views: 98

Answers (1)

Ricardo Cruz
Ricardo Cruz

Reputation: 3593

You can use np.mgrid (or np.meshgrid).

>>> np.mgrid[0:5,0:5]
array([[[0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2],
        [3, 3, 3, 3, 3],
        [4, 4, 4, 4, 4]],
       [[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]]])

If you want, use a, b = np.mgrid[0:5, 0:5] to create variable a with the first matrix, and b with the second matrix.

Please check this question for more information on this.

Upvotes: 2

Related Questions