Danielle Skinner - 2 years ago 75
Python Question

# Repeating rows and columns in Python

I'm trying to make two 600x800 matrices (X and Y) that look like the following:

-X has 0 to 600 in every row

-Y has 800 to 0 in every column

My idea was to do something along these lines:

`N = np.arange(0,600, 1)`

`M = np.arange(0, 800, 1)`

`X = np.zeros((800,600))`

`Y = np.zeros((800,600))`

And from here, put
`N`
into every row in X, and put
`M[::-1]`
into every column in Y, but I'm not sure how to go about this.. Any help is very appreciated!

You are in luck as NumPy has a built-in for exactly that task in `np.meshgrid` -

``````X,Y = np.meshgrid(N,M[::-1])
``````

Sample run -

``````In [2]: N
Out[2]: array([0, 1, 2, 3, 4, 5])

In [3]: M
Out[3]: array([0, 1, 2, 3, 4, 5, 6, 7])

In [4]: X,Y = np.meshgrid(N,M[::-1])

In [5]: X
Out[5]:
array([[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5]])

In [6]: Y
Out[6]:
array([[7, 7, 7, 7, 7, 7],
[6, 6, 6, 6, 6, 6],
[5, 5, 5, 5, 5, 5],
[4, 4, 4, 4, 4, 4],
[3, 3, 3, 3, 3, 3],
[2, 2, 2, 2, 2, 2],
[1, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0]])
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download