How to pass meshgrid as an argument to a function which only allows an array in python

1.2k Views Asked by At

I am programming in python and I want to plot a function defined by as "objFun (inputPoint, parameter2, parameter3)" with three arguments where the first argument is the point (a numpy array of 2 elements or coordinates) at which the function value is computed. My approach is

x = np.linspace(-10,10,50)
y = np.linspace(-10,10,50)
X,Y = np.meshgrid(x,y)

However I don't know how to pass X and Y as arguments to objFun since it accepts a single dimensional array of variables. I can't change the function to accept both X and Y as arguments. An example of objFun is a follows:

def objFun (x, alpha, beta):
   if alpha > 0 :
        return x[0]^2+x[1]^2
   else if beta > 0 :
        return x[0] + x[1]
   else:
        return 0

I want to feed mesh points X, Y to x[0] and x[1].

1

There are 1 best solutions below

3
Arne On BEST ANSWER

Update: Answer now includes OP's example function and shows how to pass keyword argument values.


You can combine map() and zip(), while using a lambda function construction to get the parameter values across:

import numpy as np

def objFun (x, alpha, beta):
    """example function by OP without default parameter values"""
    if alpha > 0:
        return x[0]**2 + x[1]**2
    elif beta > 0:
        return x[0] + x[1]
    else:
        return 0

x = np.linspace(-10, 10, 3) # numbers reduced to 3
y = np.linspace(-10, 10, 3) # for convenience
X,Y = np.meshgrid(x,y)

for i in map(lambda x: objFun(x, alpha=1, beta=1), zip(X.flatten(), Y.flatten())):
    print(i) # just for testing/demonstration

The output is as expected:

200.0
100.0
200.0
100.0
0.0
100.0
200.0
100.0
200.0