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

Subtract 2 different sized 2D arrays to produce a 3D array

I have two 2D arrays, one M is 2000×3 and the other N is 20×3 (sets of x,y,z coords). I would like to subtract N from M to produce a 3D array 2000x20x3. Currently I get a ValueError: operands could not be broadcast together with shapes (2000,3) (20,3)

A more simple example as a working exercise

M = np.array([[1,1,1],[2,1,1],[3,1,1],[4,1,1],[1,2,1],[2,2,1],[3,2,1],[4,2,1]])
N = np.array([[0,0,0],[1,0,0]])

M.shape = (8,3)
N.shape = (2,3)

I wish to do A=M-N to produce an 8x2x3 array, where for each value 1->M, there are N sets of differences in the x,y,z coordinates.

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

In other words:

A = array([[[1,1,1],[0,1,1]],[[2,1,1],[1,1,1]],[[3,1,1],[2,1,1]],[[4,1,1],[3,1,1]],[[1,2,1],[0,2,1]]...])

Is this possible, and if so how? Preferably without the use of any for loops

>Solution :

Use broadcasting:

A = M[:,None]-N

A.shape
# (8, 2, 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