How to fill np array with values of function?

Viewed 44

Imagine I have some function, for example

def f(x, y):
    return x * y

And I want to fill some matrix with its values. The easiest way to do is, for example

N = 10
X = np.arange(N)
Y = np.arange(N)
matrix = np.zeros((N, N))
for i, x in enumerate(X):
    for j, y in enumerate(Y):
        matrix[i][j] = f(x,y)

How can I do it in pythonic way? For example using np.vectorize?

1 Answers

Using something like np.fromfunction or np.vectorize will give you little, if any, advantage over a normal for loop. In numpy, you can take advantage of the fact that vectorized operations use loops implemented in C. The problem is that there is no general solution to vectorize your function. For the example you give, it's possible though:

x = np.arange(N)
y = np.arange(N)
matrix = x[:, None] * y

For more complex operations that can not be reduced to numpy function calls, you may want to consider using cython or numba.

Related