12

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)

3 Answers 3

30

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]]
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, how well does this scale? If I wanted to subtract 2 numpy arrays that are like 1000x1000 , it should be relatively quick?
@ScipioAfricanus Yes, doing matrix algebra with larger matrices is exactly what NumPy is great for.
4

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

1

I recommend using NumPy

X = numpy.array([
    [12,7,3],
    [4 ,5,6],
    [7 ,8,9]
])

Y = numpy.array([
    [5,8,1],
    [6,7,3],
    [4,5,9]
])

delta_r = numpy.sqrt(X ** 2 - Y ** 2)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.