Skip to main content

13.2) Operations (cont'd)


NumPy also provide mathematical functions which operate element by element on an array (again, no need to write a loop). Don’t forget the np before the function name. Most mathematical functions are available: cos, sin, tanh, log, exp:

>>> 10 * np.sin(a)
array([ 8.41470985,  9.09297427,  1.41120008, -7.56802495])

Multiplication of two arrays is also element by element. If you want a matrix product, use the NumPy dot() function.

>>> A=np.array([[1,0],[1,1]])
>>> B=np.array([[1,2],[3,4]])
>>> A * B
array([[1, 0],
       [3, 4]])
>>> np.dot(A,B)
array([[1, 2],
       [4, 6]])

You can also turn an array into a matrix (another type of data provided by NumPy) to perform matrix operations on it.