Search code examples
numpyarray-broadcastingnumpy-ufunc

Simulate numpy vectorized function on a meshgrid


This is the example given on how to use numpy.meshgrid

x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)

What if I have a meshgrid like xx,yy above, but my function is a regular function that isn't vectorized, f(x,y), for example, the regular math.sin function ?

I know I can loop through the list of lists of xx,yy, but I want to try to simulate vectorized code.


Solution

  • If you don't care the speed, you can use numpy.vectorize():

    import numpy as np
    x = np.arange(-5, 5, 0.1)
    y = np.arange(-5, 5, 0.1)
    xx, yy = np.meshgrid(x, y, sparse=True)
    z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
    
    import math
    def f(x, y):
        return math.sin(x**2 + y**2) / (x**2 + y**2)
    
    np.allclose(np.vectorize(f)(xx, yy), z)