2

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.