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

Numpy: difference between array of shape (N, 3) and array of shape (M, 3), where M < 3

I have an array of A of shape (N, 3) and an array B of shape (M, 3), where M < N.

I want to create some kind of array shape C of shape (M, N, 3), where C[i, :, :] of shape (3 ,N) is the difference between all points in A and the ith point of B:

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

Orr more explicitly:

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

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

What is the best way to do it easily with vectorized Numpy operations, without having to rely on loops?

>Solution :

You can broadcast:

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

Shapes:

# A[None].shape
(1, N, 3)

# B[:,None].shape
(M, 1, 3)

# C.shape
(M, N, 3)
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