How to calculate numpy array without for loop

Viewed 284

I have two numpy arrays with shapes A = (226, 250) and B = (195, 195, 250). I want to compute a new array C:

for i in range(A.shape[0]):
    C = A[i, :].reshape(1, 1, -1) - B        

Is there another way to calculate C without an iteration process?

2 Answers

It seems that you want

C = A[:, None, None, :] - B

None is an alias for np.newaxis. It inserts a new axis in the location you place it in the index. Just like

C = A.reshape(A.shape[0], 1, 1, A.shape[1])

You can use apply_along_axis

C = np.apply_along_axis(lambda x: x.reshape(1, 1, -1) - B, 1, A)

But keep in mind that the whole dataset is processed in the ram. This may cause an RAM issue.

Edit: The solution with C = A[:, None, None, :] - B has the same issue with the RAM.

An alternative way could be to hold the loop and use a numba decorator. This will fasten up the loop to nearly c speed and avoid flooding your RAM.

Related