Home > Blockchain >  building mask for 2d array by index
building mask for 2d array by index

Time:03-31

Consider the following mask:

def maskA(n):
    assert((n % 2) == 0)

    sample_arr = [False, False]
    bool_arr = np.random.choice(sample_arr, size=(n, n))
    # print(bool_arr.shape)

    for i in range(n):
        for j in range(n):
            if (i >= n//2) and (j < n//2):
                bool_arr[i, j] = True
            else:
                bool_arr[i, j] = False

    for i in range(n):
        for j in range(n):
            if (i < n//2) and (j >= n//2):
                bool_arr[i, j] = True or bool_arr[i, j]
            else:
                bool_arr[i, j] = False or bool_arr[i, j]
    return bool_arr

which select elements between clusters (2 x n/2 subnetworks or True elements) in a network.

[[False False False  True  True  True]
 [False False False  True  True  True]
 [False False False  True  True  True]
 [ True  True  True False False False]
 [ True  True  True False False False]
 [ True  True  True False False False]]

is it possible to make it better (shorter, cleaner, faster)?

CodePudding user response:

You can use indexing to assign values instead of using for-loops.

import numpy as np

def maskA(n):
    assert((n % 2) == 0)

    bool_arr = np.full((n, n), True)
    bool_arr[0:int(n/2), 0:int(n/2)] = False
    bool_arr[int(n/2):n, int(n/2):n] = False

    return bool_arr


print(maskA(8))
  • Related