Home > Blockchain >  Numpy subtraction of every pair of elements of vector
Numpy subtraction of every pair of elements of vector

Time:10-24

Given a numpy array, say

x = np.array(
[[0],
 [1],
 [2]]
)

I would like to find the matrix containing a-b for every possible pair a,b in x. I.e.

[[0-0, 0-1, 0-2]
 [1-0, 1-1, 1-2]
 [2-0, 2-1, 2-2]]
==
[[ 0, -1, -2]
 [ 1,  0, -1]
 [ 2,  1,  0]]

I am avoiding using a for loop for the sake of efficiency.

CodePudding user response:

As Michael wrote, numpy broadcasting can help you with this. If you try to perform an operation on a vector a with shape (3,1) with vector b with shape (1,3), numpy under the treats it as if the rows of a were repeated across the columns and columns of b where repeated across the rows result in the operations you described.

That's why Michael told you to subtract the transpose of the first vector with itself to recover the result you asked for. x-x.T

Broadcasting is good because it acheives this with striding, and most of the time uses less memory.

In the more general case, a and b do not have the same length for this to work. There are more details here: https://numpy.org/doc/stable/user/basics.broadcasting.html

  • Related