numpy.fromfunction

numpy.fromfunction(function, shape, **kwargs)

Construct an array by executing a function over each coordinate.

The resulting array therefore has a value fn(x, y, z) at coordinate (x, y, z).

Parameters:

fn : callable

The function is called with N parameters, each of which represents the coordinates of the array varying along a specific axis. For example, if shape were (2, 2), then the parameters would be two arrays, [[0, 0], [1, 1]] and [[0, 1], [0, 1]]. fn must be capable of operating on arrays, and should return a scalar value.

shape : (N,) tuple of ints

Shape of the output array, which also determines the shape of the coordinate arrays passed to fn.

dtype : data-type, optional

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

See also

indices, meshgrid

Notes

Keywords other than shape and dtype are passed to the function.

Examples

>>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
array([[ True, False, False],
       [False,  True, False],
       [False, False,  True]], dtype=bool)
>>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
array([[0, 1, 2],
       [1, 2, 3],
       [2, 3, 4]])

Previous topic

numpy.fromfile

Next topic

numpy.fromiter

This Page

Quick search