Search code examples
pythonarraysnumpymultiplication

Elements multiplication in NumPy array with all other elements


If I have a NumPy array [a b c d], is there a way to get the sum of the multiplication of each element with all other elements excluding itself and without duplicates?

For example, the sum for this array would be: ab + ac + ad + bc + bd + cd.

Using for loops is an option, but it wouldn't be very efficient when you have very large arrays. So I was wondering if there is a more efficient way in NumPy.


Solution

  • Using math, you can refactor the sum of product into a product of sums.

    a*b + a*c + a*d + b*c + b*d + c*d
    
    (a+b+c)*d + (a+b)*c + a*b
    

    This gives you the following:

    out = (a[1:]*np.cumsum(a[:-1])).sum()
    

    Or better, use matrix multiplication:

    out = a[1:] @ a[:-1].cumsum()
    

    Example:

    a = np.array([3, 6, 4, 9, 10])
    
    np.triu(a*a[:,None], k=1).sum()
    # 391
    
    a[1:] @ a[:-1].cumsum()
    # 391