Absolute Difference Of Two NumPy Arrays


Answer :

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]] 

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)) 

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?