pythonarraysnumpylinear-algebran-dimensional

Numpy Matrix Subtraction Different Dimensions


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.


Solution

  • 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.