Skip to content Skip to sidebar Skip to footer

Calculate All Possible Columnwise Differences In A Matrix

I would like to compute all possible pairwise differences (without repetition) between the columns of a matrix. What's an efficient / pythonic way to do this? mat = np.random.norm

Solution 1:

In [7]: arr = np.arange(m*n).reshape((m, n))

In [8]: arr
Out[8]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])

In [9]: from itertools import combinations

In [10]: def diffs(arr):
   ....:     arr = np.asarray(arr)
   ....:     n = arr.shape[1]
   ....:     for i, j in combinations(range(n), 2):
   ....:         yield arr[:, i] - arr[:, j]
   ....:         

In [11]: for x in diffs(arr): print x
[-1 -1 -1 -1 -1]
[-2 -2 -2 -2 -2]
[-3 -3 -3 -3 -3]
[-1 -1 -1 -1 -1]
[-2 -2 -2 -2 -2]
[-1 -1 -1 -1 -1]

If you need them in an array, then just preallocate the array and assign the rows (or columns, as desired).

Solution 2:

Incidentally, here is the solution I came up with. Much less elegant than moarningsun's.

def pair_diffs(mat):
    n_pairs = int(sp.misc.comb(mat.shape[1], 2))
    pairs = np.empty([mat.shape[0], n_pairs])

    this_pair = 0

    # compute all differences:
    for i in np.arange(mat.shape[1]-1):
        for j in np.arange(i+1, mat.shape[1]):
            pairs[:, this_pair] = mat[:, i] - mat[:, j]
            this_pair += 1
    return pairs

Post a Comment for "Calculate All Possible Columnwise Differences In A Matrix"