numpy.fromfunction#

numpy.fromfunction(function,shape,*,dtype=<class'float'>,like=None,**kwargs)[source]#

Construct an array by executing a function over each coordinate.

The resulting array therefore has a valuefn(x,y,z) atcoordinate(x,y,z).

Parameters:
functioncallable

The function is called with N parameters, where N is the rank ofshape. Each parameter represents the coordinates of the arrayvarying along a specific axis. For example, ifshapewere(2,2), then the parameters would bearray([[0,0],[1,1]]) andarray([[0,1],[0,1]])

shape(N,) tuple of ints

Shape of the output array, which also determines the shape ofthe coordinate arrays passed tofunction.

dtypedata-type, optional

Data-type of the coordinate arrays passed tofunction.By default,dtype is float.

likearray_like, optional

Reference object to allow the creation of arrays which are notNumPy arrays. If an array-like passed in aslike supportsthe__array_function__ protocol, the result will be definedby it. In this case, it ensures the creation of an array objectcompatible with that passed in via this argument.

New in version 1.20.0.

Returns:
fromfunctionany

The result of the call tofunction is passed back directly.Therefore the shape offromfunction is completely determined byfunction. Iffunction returns a scalar value, the shape offromfunction would not match theshape parameter.

Notes

Keywords other thandtype andlike are passed tofunction.

Examples

>>>importnumpyasnp>>>np.fromfunction(lambdai,j:i,(2,2),dtype=float)array([[0., 0.],       [1., 1.]])
>>>np.fromfunction(lambdai,j:j,(2,2),dtype=float)array([[0., 1.],       [0., 1.]])
>>>np.fromfunction(lambdai,j:i==j,(3,3),dtype=int)array([[ True, False, False],       [False,  True, False],       [False, False,  True]])
>>>np.fromfunction(lambdai,j:i+j,(3,3),dtype=int)array([[0, 1, 2],       [1, 2, 3],       [2, 3, 4]])
On this page