I am using np.fromfunction
to create an array of a specific sized based on a function. It looks like this:
import numpy as np
test = [[1,0],[0,2]]
f = lambda i, j: sum(test[i])
matrix = np.fromfunction(f, (len(test), len(test)), dtype=int)
However, I receive the following error:
TypeError: only integer arrays with one element can be converted to an index
The function needs to handle numpy arrays. An easy way to get this working is:
import numpy as np
test = [[1,0],[0,2]]
f = lambda i, j: sum(test[i])
matrix = np.fromfunction(np.vectorize(f), (len(test), len(test)), dtype=int)
np.vectorize
returns a vectorized version of f, which will handle the arrays correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With