I want to populate a matrix by function f() which consumes arrays a, b, c and d:
A nested loop is possible but I'm looking for a faster way. I tried np.fromfunction with no luck. Function f has a conditional so the solution should preferably support conditionals. Example function:
def f(a,b,c,c):
return a+b+c+d if a==b else a*b*c*d
How np.fromfunction failed:
>>> a = np.array([1,2,3,4,5])
>>> b = np.array([10,20,30])
>>> def f(i,j): return a[i] * b[j]
>>> np.fromfunction(f, (3,5))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Anaconda3\lib\site-packages\numpy\core\numeric.py", line 1853, in fromfunction
return function(*args, **kwargs)
File "<stdin>", line 1, in fun
IndexError: arrays used as indices must be of integer (or boolean) type

fromfunctionor nested loops seems the best way. What did you try that you say you had no luck with?ifcondition could be vectorized so you don't need a call tofromfunction, which would have to call yourfunctionfor every index. Thefromfunctionthat failed includes an indexing operation. Is this a part of the function you actually want? Your example could be recreated withoutfromfunctionby adding an axis toband broadcasting:b[:, None] * agives you the 3x5 array where the(i, j)element is a multiplication ofa[j]andb[i]fundoesn't really make sense: do you want to return the sum (or product) of the indices (which is whata,bc,d) are, or do you want to return the values at those indices in the arrays? Did you meandef fun(i, j): return a[i]+b[i]+c[i]+d[j] if i==j else a[i]*b[i]*c[i]*d[j]