-1

I don't want any for loop and was wondering if there is a function I can use.

5
  • Element-wise squaring? Commented Apr 1, 2016 at 3:53
  • Yes. [[1,2,3], [2,3,4]] becomes [[1,4,9],[2,9,16]] Commented Apr 1, 2016 at 3:56
  • @Jobs I think you mean that list becomes [[1,4,9],[4,9,16]] Commented Apr 1, 2016 at 4:29
  • Yes - you are right. @AntonProtopopov Commented Apr 1, 2016 at 4:31
  • docs.scipy.org/doc/numpy-dev/user/… Commented Apr 1, 2016 at 4:36

3 Answers 3

6

If A was the numpy array, I would just type in A*A.

Sign up to request clarification or add additional context in comments.

Comments

5

As K. Tom suggested you can do A * A you can also do A ** 2

import numpy as np

array = np.array([1,2,3])

print array * array #[1 4 9]
print array ** 2    #[1 4 9]

2 Comments

I definitely did not know that! Thanks.
The only thing to take care of is the type. a = np.array([[100, 200], [50, 150]], dtype=np.uint8); a*a will overflow.
2

You could use np.square or np.power:

l =  [[1,2,3], [2,3,4]]

In [5]: np.power(l, 2)
Out[5]:
array([[ 1,  4,  9],
       [ 4,  9, 16]], dtype=int32)

In [6]: np.square(l)
Out[6]:
array([[ 1,  4,  9],
       [ 4,  9, 16]], dtype=int32)

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.