Search code examples
pythonnumpyarray-difference

How to construct a matrix of all possible differences of a vector in numpy


I have a one dimensional array, lets say:

import numpy as np
inp_vec = np.array([1, 2, 3])

Now, I would like to construct a matrix of the form

[[1 - 1, 1 - 2, 1 - 3],
 [2 - 1, 2 - 2, 2 - 3],
 [3 - 1, 3 - 2, 3 - 3]])

Of course it can be done with for loops but is there a more elegant way to do this?


Solution

  • This seems to work:

    In [1]: %paste
    import numpy as np
    inp_vec = np.array([1, 2, 3])
    
    ## -- End pasted text --
    
    In [2]: inp_vec.reshape(-1, 1) - inp_vec
    Out[2]: 
    array([[ 0, -1, -2],
           [ 1,  0, -1],
           [ 2,  1,  0]])
    

    Explanation:

    You first reshape the array to nx1. When you subtract a 1D array, they are both broadcast to nxn:

    array([[ 1,  1,  1],
           [ 2,  2,  2],
           [ 3,  3,  3]])
    

    and

    array([[ 1,  2,  3],
           [ 1,  2,  3],
           [ 1,  2,  3]])
    

    Then the subtraction is done element-wise, which yields the desired result.