Home > OS >  Creating NxN matrix where each cell has the value of the nxn matrix it represents inside the large N
Creating NxN matrix where each cell has the value of the nxn matrix it represents inside the large N

Time:12-12

Given NxN dimensions, I'm traying to create a functions that returns a list of values that represent cells from the NxN matrix. for example:

a_3x3 = [   # 3x3 pixel window
    [3,3,3],
    [3,1,3],
    [3,3,3]
    ]
a_3x3_lis = [3, 3, 3, 3, 1, 3, 3, 3, 3] # same window flattend

a_5x5 = [       # 5x5 pixel window
    [5,5,5,5,5],
    [5,3,3,3,5],
    [5,3,1,3,5],
    [5,3,3,3,5],
    [5,5,5,5,5]
    ]
a_5x5_lis = [5, 5, 5, 5, 5, 5, 3, 3, 3, 5, 5, 3, 1, 3, 5, 5, 3, 3, 3, 5, 5, 5, 5, 5, 5] # same window flattened

I've just created the lists manually so far but its no good for large matrixes

near_win_3x3 = [3, 3, 3, 3, 1, 3, 3, 3, 3]
near_win_5x5 = [5, 5, 5, 5, 5, 5, 3, 3, 3, 5, 5, 3, 1, 3, 5, 5, 3, 3, 3, 5, 5, 5, 5, 5, 5]
near_win_7x7 = [7, 7, 7, 7, 7, 7, 7, 7, 5, 5, 5, 5, 5, 7, 7, 5, 3, 3, 3, 5, 7, 7, 5, 3, 1, 3, 5, 7, 7, 5, 3, 3, 3, 5, 7, 7, 5, 5, 5, 5, 5, 7, 7, 7, 7, 7, 7, 7, 7,]

CodePudding user response:

The values in your array are a function of their manhattan distance to the center. To be specific, it's: f(d) = 1 2 * d.

import numpy as np

N = 7
a_NxN = 1   2 * abs(np.stack(np.mgrid[:N, :N]) - (N - 1) // 2).max(0)

This produces:

[[7 7 7 7 7 7 7]
 [7 5 5 5 5 5 7]
 [7 5 3 3 3 5 7]
 [7 5 3 1 3 5 7]
 [7 5 3 3 3 5 7]
 [7 5 5 5 5 5 7]
 [7 7 7 7 7 7 7]]

CodePudding user response:

One way using numpy.minimum:

def reversed_pyramid(n):
    a = np.arange(n)
    m = np.minimum(a, a[::-1])
    return n - np.minimum.outer(m, m) * 2

Output:

# reversed_pyramid(7)
array([[7, 7, 7, 7, 7, 7, 7],
       [7, 5, 5, 5, 5, 5, 7],
       [7, 5, 3, 3, 3, 5, 7],
       [7, 5, 3, 1, 3, 5, 7],
       [7, 5, 3, 3, 3, 5, 7],
       [7, 5, 5, 5, 5, 5, 7],
       [7, 7, 7, 7, 7, 7, 7]])
  • Related