3

I have two numpy matrices. One contains lambda functions. The other contains values.

Is there a function that is similar to Python's map function that will allow me to get the expected result?

Is there a better way?

functionMatrix = np.array([[lambda x:x**2, lambda x:x**3],[lambda x: x**2, 
lambda x: np.sqrt(x)]])
valueMatrix = np.array([[1,2],[3,4]])

expectedResult = np.array([[1,8],[9,2]])
3
  • 1
    If it's always simple exponents you're trying to get, you could just avoid the lambdas, and do something like : functionMatrix = np.array([[2, 3],[2, 0.5]]) and then valueMatrix ** functionMatrix (output: array([[ 1., 8.], [ 9., 2.]])). Also, judging by your expected output, I think you mean lambda x: x**2 instead of lambda x: x*2, and np.sqrt instead of np.square Commented May 8, 2018 at 20:27
  • sacul - You're right, let me fix that. It won't always be simple exponents. Some functions might be natural log, inverse, etc. Commented May 8, 2018 at 20:33
  • "is there a better way?" depends on if there's a mathematical relationship to all your lambda functions. Putting them inside a numpy array nets you an 'object array' which is a convenience feature built into numpy, but it does not take advantage of many of the benefits of a normal array (from a speed or memory standpoint). Commented May 8, 2018 at 20:47

1 Answer 1

3

This is just syntactic sugar but does the job.

@np.vectorize
def apply_vec(f, x):
    return f(x)

result = apply_vec(functionMatrix, valueMatrix)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.