0

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

1 Answer 1

1

I think numpy broadcasting will meet all of your criteria ;)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.