how to broadcast a sympy lambdify generated function?

I'd like to compute a Sympy expression as a function of two of the symbols in it. A function of 1 variable can readily be broadcast-ed after lambdifying it:

x, y, z = symbols('x y z')
expr = x*y + z
f = lambdify(x, expr.subs({z:2, y:4}))
x = np.linspace(1, 4, 5)

But is there a way to use some builtin capability of numpy or sympy to broadcast higher dimensionally? In other words, is there a more direct or cleaner way to do the following?

x, y, z = symbols('x y z')
expr = x*y + z
f = lambdify([x, y], expr.subs({z:2}))
def g(xy):
    k = xy.shape[1]
    a = np.ndarray((k,k))
    for j in range(k): 
        for i in range(k):
            a[j, i] = f(xy[0, j], xy[1, i])
    return a

x = np.linspace(0, 4, 5)
y = np.linspace(10, 12, 5)
xy = np.array([x,y])  

Read more here:

Content Attribution

This content was originally published by Erik Iverson at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: