Home > database >  Subtract 2 different sized 2D arrays to produce a 3D array
Subtract 2 different sized 2D arrays to produce a 3D array

Time:11-23

I have two 2D arrays, one M is 2000x3 and the other N is 20x3 (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.

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

CodePudding user response:

Use broadcasting:

A = M[:,None]-N

A.shape
# (8, 2, 3)
  • Related