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?
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]])
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
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)