Computing a function for all elements of an array

All scalar functions defined in NumPy follow the ufunc protocol, so that when applied to an array, they are applied to every array item. The following example shows you how to compute the sine function for all elements of a one-dimensional array:

x = np.pi * np.arange(0, 2, 0.25)
y = np.sin(x)

In this code, we first create an array x with equally spaced values. Then, with the np.sin(x) expression, we compute an array y containing the value of the sine function evaluated at each item of the array x

It is important to notice that ufunc functions will operate on arrays with an arbitrary number of dimensions. For a unary ufunc, that is, a function that admits a single argument, the shape of the returned value is the same as the shape of the input.

Keep in mind that ufunc functions always operate on an element-by-element basis. For example, if A is a two-dimensional square array, the np.exp(A) expression computes the exponential of each element of A. This should not be confused with the exponential of a square matrix A, which is a different concept. Matrix operations are dealt with later in this book, in Chapter 5, Matrices and Linear Algebra.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset