[SOLVED] Generate array from elementwise operation of vector with itself

Issue

What is the "best" way to generate an array from performing an operation between each element of a vector and the whole vector?

The below example uses a loop and subtraction as the operation but in the general case, the operation could be any function.

Criteria for "best" could be: execution speed, amount of code needed, readability

a = np.array([1, 2, 3])
dim = len(a)
b = np.empty([dim, dim])

def operation(x1, x2):
  return x1-x2

for i in range(dim):
  b[i,:] = operation(a, a[i])

print(b)

Solution

I think numpy broadcasting will meet all of your criteria 😉

>>> a - a[:, None]
array([[ 0,  1,  2],
       [-1,  0,  1],
       [-2, -1,  0]])

Answered By – richardec

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *