Aleks Vujic
Aleks Vujic

Reputation: 2251

Numpy matrix with values equal to offset from central row/column

For given odd value a, I want to generate two matrices, where values represent the offset from central row/column in x or y direction. Example for a=5:

    | -2 -1 0 1 2 |        | -2 -2 -2 -2 -2 |
    | -2 -1 0 1 2 |        | -1 -1 -1 -1 -1 |
X = | -2 -1 0 1 2 |    Y = |  0  0  0  0  0 |
    | -2 -1 0 1 2 |        |  1  1  1  1  1 |
    | -2 -1 0 1 2 |        |  2  2  2  2  2 |

What is the easiest way to achieve this with Numpy?

Upvotes: 1

Views: 75

Answers (3)

Quang Hoang
Quang Hoang

Reputation: 150765

Try meshgrid:

n=5
X,Y = np.meshgrid(np.arange(n),np.arange(n))
X -= n//2
Y -= n//2

Or

n = 5
range_ = np.arange(-(n//2), n-n//2)
X,Y = np.meshgrid(range_, range_)

Also check out ogrid.

Upvotes: 1

Michael
Michael

Reputation: 2367

Just use fancy indexing technique of Numpy module. The following code demonstrates the solution for a 5X5 matrix:

import numpy as np


if __name__=='__main__':
    A = np.zeros((5, 5))
    A[np.arange(5), :] = np.arange(5)//2 - np.arange(5)[::-1]//2

    B = np.zeros((5, 5))
    B[:, np.arange(5)] = np.arange(5)//2 - np.arange(5)[::-1]//2
    B = B.T

Output

[[-2. -1.  0.  1.  2.]
 [-2. -1.  0.  1.  2.]
 [-2. -1.  0.  1.  2.]
 [-2. -1.  0.  1.  2.]
 [-2. -1.  0.  1.  2.]]
[[-2. -2. -2. -2. -2.]
 [-1. -1. -1. -1. -1.]
 [ 0.  0.  0.  0.  0.]
 [ 1.  1.  1.  1.  1.]
 [ 2.  2.  2.  2.  2.]]

Cheers.

Upvotes: 1

Mustafa Aydın
Mustafa Aydın

Reputation: 18306

np.arange and np.repeat will do:

a = 5

limits = -(a//2), a//2 + 1
col = np.c_[np.arange(*limits)]

Y = np.repeat(col, repeats=a, axis=1)
X = Y.T

Upvotes: 1

Related Questions