1

Say I have a numpy array [[1,2],[3,4],[5,6]], how do I do element-wise mathematics such that I could iterate over each XY pair to get X^2 + Y^2 for each pair?

2 Answers 2

2

Since you tagged numpy:

(np.array(a)**2).sum(-1)

Output:

array([ 5, 25, 61])
Sign up to request clarification or add additional context in comments.

Comments

0
import numpy as np

arr1 = np.array([[1,2],[3,4],[5,6]])
    
rows = arr1.shape[0] 
cols = arr1.shape[1]
    
ans = []
   
for x in range(rows):
    answer = arr1[x,0]**2 + arr1[x,1]**2
    ans.append(answer)
print(ans)

1 Comment

Why did you iterate? Since you have an array just do: (arr1**2).sum(axis=1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.