1

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.

4

1 回答 1

2

你很幸运,因为 NumPy 有一个内置的功能,用于执行该任务np.meshgrid-

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

样品运行 -

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]])

由于问题也被标记为NumPy broadcasting,我会在用零初始化后添加另一种使用它的方法(如问题中所列),如下所示 -

m,n = M.size, N.size    # Size parameters

X = np.zeros((m,n),dtype=N.dtype)
Y = np.zeros((m,n),dtype=M.dtype)

X += N
Y += M[::-1,None]
于 2016-05-31T21:04:22.867 回答