Search code examples
pythonnumpyscipyarray-broadcasting

Pairwise difference of vectors


Say i have a matrix that is composed of N vectors as columns: matrix=[v_1, v_2, .. v_N] where v is from R^N. I want a new matrix that gives: for all (r in N, s in N) v(r)-v(s). For example if N=3, then i want a 3x3x3 and for a particular index i,j,k, it Represents the kth index of v(i)-v(j).


Solution

  • You can use broadcasting on a new dimension:

    out = matrix[:,None]-matrix
    

    Example:

    matrix = np.arange(9).reshape(3,3)
    out = matrix[:,None]-matrix
    

    Output:

    array([[[ 0,  0,  0],
            [-3, -3, -3],
            [-6, -6, -6]],
    
           [[ 3,  3,  3],
            [ 0,  0,  0],
            [-3, -3, -3]],
    
           [[ 6,  6,  6],
            [ 3,  3,  3],
            [ 0,  0,  0]]])