Home > Enterprise >  Numpy sum of minimums of two arrays like dot product efficiently
Numpy sum of minimums of two arrays like dot product efficiently

Time:01-19

I would like get two arrays' sum of minumums efficiently with numpy. For example;

X=np.array([[1,2,3],[1,2,0]])
Y=np.array([[0,2,0],[1,3,1]])

My result should be;

result = array([[2, 4],[2, 3]])

The calculation for first cell;

result[0,0] = min(X[0,0],Y[0,0])  min(X[0,1],Y[0,1]) min(X[0,2],Y[0,2])

In general, the result should be:

res[i,j] = sum(np.minimum(X[i, :], Y[j, :]))

but more efficently.

CodePudding user response:

Best I could do:

import numpy as np


def sum_mins(x, y):
    mask = (X - Y) < 0
    return np.sum(X*mask   Y*np.logical_not(mask))


X=np.array([1,2,3])
Y=np.array([0,2,0])

print(sum_mins(X, Y))

CodePudding user response:

One naive approach close to definition:

result = np.array([[np.sum(np.minimum(v_x, v_y)) for v_y in Y] for v_x in X])
  •  Tags:  
  • Related