Numpy vectorized function assignment with a boolean statement

Viewed 1224

I would like to assign a function that has a boolean evaluation in it, using a fast way. Here is a simple example. I want the following function to be evaluated for arbitrary a and b:

a = 0.5
b = 0.6
def func(x):
    x=max(x,a)
    if x>b:
        return x**2
    else:
        return x**3

and then I want to assign the function values into an array in a vectorized manner (for speed):

xRange = np.arange(0, 1, 0.1)
arr_func = func(xRange)

But I get the error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Now, I know I can assign the values in a loop. But that will be slow compared to the vectorized equivalent. Can I bypass this exception and still assign the values in a vectorized manner?

3 Answers
Related