Leb_Broth
Leb_Broth

Reputation: 1111

Fastest way to build a Matrix with a custom architecture

What's the fastest way in numpy or pandas to build a matrix that has this form:

1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1

That preserves both odd and even architectures?

Upvotes: 2

Views: 102

Answers (1)

Divakar
Divakar

Reputation: 221614

Using NumPy brodacasting!

In [289]: a = np.array([1,2,3,2,1])

In [290]: np.minimum(a[:,None],a)
Out[290]: 
array([[1, 1, 1, 1, 1],
       [1, 2, 2, 2, 1],
       [1, 2, 3, 2, 1],
       [1, 2, 2, 2, 1],
       [1, 1, 1, 1, 1]])

To build the range array, we can do something like this -

In [303]: N = 3

In [304]: np.concatenate((np.arange(1,N+1),np.arange(N-1,0,-1)))
Out[304]: array([1, 2, 3, 2, 1])

Adding some bias

Let's say we want to move the highest number/peak up or down. We need to create another biasing array and use the same strategy of broadcasting, like so -

In [394]: a = np.array([1,2,3,2,1])

In [395]: b = np.array([2,3,2,1,0]) # Biasing array

In [396]: np.minimum(b[:,None],a)
Out[396]: 
array([[1, 2, 2, 2, 1],
       [1, 2, 3, 2, 1],
       [1, 2, 2, 2, 1],
       [1, 1, 1, 1, 1],
       [0, 0, 0, 0, 0]])

Similarly, to have the bias shifted left or right, modify a, like so -

In [397]: a = np.array([2,3,2,1,0]) # Biasing array

In [398]: b = np.array([1,2,3,2,1])

In [399]: np.minimum(b[:,None],a)
Out[399]: 
array([[1, 1, 1, 1, 0],
       [2, 2, 2, 1, 0],
       [2, 3, 2, 1, 0],
       [2, 2, 2, 1, 0],
       [1, 1, 1, 1, 0]])

Upvotes: 5

Related Questions