Home > Back-end >  Python: Obtain a matrix containing all differences between all elements from another matrix
Python: Obtain a matrix containing all differences between all elements from another matrix

Time:04-17

I need to calculate all differences (in absolute value) between all combinations of the elements from a given matrix. For example, given some matrix M such as

M = [[1 2]
 [5 8]]

I need to obtain a matrix X defined as

X = [[1 4 7]
[1, 3, 6]
[4, 3, 3]
[7, 6, 3]]

where I associated each row to each element in M and each column with its substraction from every other element (except with itself). I've been trying to make some for cicles, but I haven't been able to get something close to what I want.

In my code, I used numpy, thus defining all the matrices as

M = np.zeros([nx, ny])

and then replacing the values as the code progresses such as

M[i, j] = 5

CodePudding user response:

While this can be easily done by looping over elements, here is a faster and more pythonic way.

import numpy as np

M = np.array([[1,2],[5,8]])

# flatten M matrix
flatM = M.reshape(-1) 

# get all pairwise differences
X = flatM[:,None] - flatM[None,:]

# remove diagonal elements, since you don't want differences between same elements
mask = np.where(~np.eye(X.shape[0],dtype=bool))
X = X[mask]

# reshape X into desired form
X = X.reshape(len(flatM),-1)

# take absolute values
X = np.abs(X)

print(X)

Removal of diagonal elements was done using approach suggested here How to get indices of non-diagonal elements of a numpy array?

CodePudding user response:

Sensibly the same approach as the very good answer of @wizzzz1, but with a simpler syntax and faster execution:

a = M.ravel()
X = (abs(a-a[:, None])
     [~np.eye(M.size, dtype=bool)]
     .reshape(-1, M.size-1)
     )

Output:

array([[1, 4, 7],
       [1, 3, 6],
       [4, 3, 3],
       [7, 6, 3]])
  • Related