Most efficient way to mask a 4D Boolean array with a 2D Boolean mask.
I tried two methods:
A. Reshape mask to 4D and mask
B. Reshape the inverted mask to 4D and product two matrixes
import numpy as np
import time
I = 150
J = 2000
K = I
S = 25
matrix_to_mask = np.random.choice(a=[True, False], size=(I, J, K, S))
mask_2d = np.random.choice(a=[True, False], size=(I, S))
t = time.time()
matrix_to_mask[np.tile(mask_2d[:, np.newaxis, np.newaxis, :], (1, J, K, 1))] = False
print("Mask: " + str(time.time() - t)) # 2.77 sec
t = time.time()
a = matrix_to_mask * np.tile(np.invert(mask_2d)[:, np.newaxis, np.newaxis, :], (1, J, K, 1))
print("Product: " + str(time.time() - t)) # 1 sec
Is there any other method which will speed up the mask?
Thanks