0

Suppose I have a function that receive 3 parameters:

def foo(x, y, fac):
  return x * y * fac

How do I create a 2D numpy array, who's values will be the result of the above function when the parameters are the new array own x, y values?

1
  • Can you provide example of the input array? Not sure what you are trying to do. Commented Feb 13, 2015 at 6:50

2 Answers 2

1

Numpy already has a function called meshgrid. You would say:

x = np.array([1,2,3])
y = np.array([4,5,6])
X, Y = np.meshgrid(x, y)
result = foo(X, Y, 0.03)
Sign up to request clarification or add additional context in comments.

Comments

0

I guess this is what you want to accomplish. I don't know if you can speed it up by getting rid of the loop though.

import numpy as np

def foo(x, y, fac):
    return x * y * fac

def make2dmatrix(a, b):
    C = np.zeros(shape=[a.size, b.size])
    for i in range(a.size):
        C[i, :] = foo(a[i], b, fac=0.5)
    return C

if __name__ == '__main__':
    a = np.array([1, 2, 3])
    b = np.array([2, 3, 4])
    print (make2dmatrix(a, b))

Outcome

[[ 1.   1.5  2. ]
 [ 2.   3.   4. ]
 [ 3.   4.5  6. ]]

1 Comment

range and numpy within one method are usually not an optimal match.

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.