0

I currently have a 5D numpy array of dimensions 40 x 3 x 3 x 5 x 1000 where the dimensions are labelled by a x b x c x d x e respectively.

I have another 2D numpy array of dimensions 3 x 1000 where the dimensions are labelled by b x e respectively.

I wish to subtract the 5D array from the 2D array.

One way I was thinking of was to expand the 2D into a 5D array (since the 2D array does not change for all combinations of the other 3 dimensions). I am not sure what array method/numpy function I can use to do this.

I tend to start getting lost with nD array manipulations. Thank you for assisting.

2 Answers2

1

IIUC, suppose your arrays are a and b:

np.swapaxes(np.swapaxes(a, 1, 3) - b, 1, 3)
Bruno Mello
  • 4,448
  • 1
  • 9
  • 39
1
In [217]: a,b,c,d,e = 2,3,4,5,6                                                                        
In [218]: A = np.ones((a,b,c,d,e),int); B = np.ones((b,e),int)                                         
In [219]: A.shape                                                                                      
Out[219]: (2, 3, 4, 5, 6)
In [220]: B.shape                                                                                      
Out[220]: (3, 6)
In [221]: B[None,:,None,None,:].shape   # could also use reshape()                                                               
Out[221]: (1, 3, 1, 1, 6)
In [222]: C = B[None,:,None,None,:]-A                                                                  
In [223]: C.shape                                                                                      
Out[223]: (2, 3, 4, 5, 6)

The first None isn't essential; numpy will add it as needed, but as a human it might help to see it.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Thank you for showing that it does broadcast. Would you happen to know how it broadcasts? Currently I've been using tile and reshape to expand my 2D matrix into a 5D matrix then performing a subtraction. Does it repeat the 2D matrix along the other axes (similar to tile + reshape). On another note, I think I may be stuck consuming more memory and increasing dimensions on the 2D matrix. I have to do logical operations with masks later on and I'm not sure how to use a 5D mask for a 2D matrix. I appreciate your answer though – tryingtocode101 Apr 10 '20 at 00:40
  • The expansion is virtual, without copies or extra memory. The details involve `strides` – hpaulj Apr 10 '20 at 01:50