Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

building mask for 2d array by index

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading