2

Here an array of functions is generated. Is there some vectorized way (ie. not an explicit loop) of calling them?

Example:

funcs = np.array(lambda x: 2*x, lambda x: 2.5*x)#in principle more funcs
args = np.array([3.0,4.0])

# numpy array of func[0](arg[0]), func[1](arg[1])
#output : array([6.0,10.0])

The functions are assumed to have the same signature, but are assumed to be non-trivial (eg. spline functions of a set of curves), and completely independent of eachother.

2 Answers 2

1

You could use itertools.imap as follows:

from itertools import imap
import numpy as np

funcs = np.array([lambda x: 2*x, lambda x: 2.5*x])
args = np.array([3.0,4.0])
answer = np.fromiter(imap(lambda func, arg: func(arg), funcs, args),float)
print(answer)

Output

[6.0, 10.0]
Sign up to request clarification or add additional context in comments.

1 Comment

I accepted your answer, but changed from converting the iterable to numpy array instead of list.
1

without import anything, try this:

import numpy as np
funcs = np.array(lambda x: 2*x, lambda x: 2.5*x)#in principle more funcs
args = np.array([3.0,4.0])

output = map(lambda x,y:x(y), funcs, args)

it works also on list and tuple.

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.