Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute difference of two NumPy arrays

Is there an efficient way/function to subtract one matrix from another and writing the absolute values in a new matrix? I can do it entry by entry but for big matrices, this will be fairly slow...

For example:

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]

for i in range(len(r_0)):
    for j in range(len(r)):
        delta_r[i][j]= sqrt((r[i][j])**2 - (r_0[i][j])**2)
like image 781
Array Avatar asked Jul 04 '16 07:07

Array


2 Answers

If you want the absolute element-wise difference between both matrices, you can easily subtract them with NumPy and use numpy.absolute on the resulting matrix.

import numpy as np

X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[5,8,1],
[6,7,3],
[4,5,9]]

result = np.absolute(np.array(X) - np.array(Y))

Outputs:

[[7 1 2]
 [2 2 3]
 [3 3 0]]

Alternatively (although unnecessary), if you were required to do so in native Python you could zip the dimensions together in a nested list comprehension.

result = [[abs(a-b) for a, b in zip(xrow, yrow)]
          for xrow, yrow in zip(X,Y)]

Outputs:

[[7, 1, 2], [2, 2, 3], [3, 3, 0]]
like image 75
miradulo Avatar answered Nov 15 '22 19:11

miradulo


Doing this becomes trivial if you cast your 2D arrays to numpy arrays:

import numpy as np

X = [[12, 7, 3],
     [4,  5, 6],
     [7,  8, 9]]

Y = [[5,  8, 1],
     [6,  7, 3],
     [4,  5, 9]]

X, Y = map(np.array, (X, Y))

result = X - Y

Numpy is designed to work easily and efficiently with matrices.

Also, you spoke about subtracting matrices, but you also seemed to want to square the individual elements and then take the square root on the result. This is also easy with numpy:

result = np.sqrt((A ** 2) - (B ** 2))
like image 29
cs95 Avatar answered Nov 15 '22 18:11

cs95