10

I wish to initialise a matrix A, using the equation A_i,j = f(i,j) for some f (It's not important what this is).

How can I do so concisely avoiding a situation where I have two for loops?

2 Answers 2

12

numpy.fromfunction fits the bill here.

Example from doc:

>>> import numpy as np
>>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
array([[0, 1, 2],
   [1, 2, 3],
   [2, 3, 4]])
1
  • 7
    Warning: the documentation does not explain this clearly, but np.fromfunction(f, shape, dtype=dtype) is a thin wrapper around f(*np.indices(shape, dtype=dtype)). It does not perform an individual call to f for each cell, so if you pass it a function that doesn't work in a vectorized manner, you'll get weird and erroneous results. May 31, 2015 at 1:19
2

One could also get the indexes of your array with numpy.indices and then apply the function f in a vectorized fashion,

import numpy as np

shape = 1000, 1000

Xi, Yj = np.indices(shape)

A = (2*Xi + 3*Yj).astype(np.int) # or any other function f(Xi, Yj)

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.