I am using Matplotlib and Numpy to produce some plots. I wish to define a function which given an array returns another array with values calculated elementwise, for example:
def func(x):
return x*10
x = numpy.arrange(-1,1,0.01)
y = func(x)
This is fine. Now however I wish to have an if-statement inside func
, for example:
def func(x):
if x<0:
return 0
else:
return x*10
x = numpy.arrange(-1,1,0.01)
y = func(x)
This unfortunately throws the following error
Traceback (most recent call last):
File "D:\Scripts\test.py", line 17, in <module>
y = func(x)
File "D:\Scripts\test.py", line 11, in func
if x<0:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I looked at the documentation for all()
and any()
and they do not fit the bill for what I need. So is there a nice way to make the function handle arrays element wise as in the first example?
x
asint
or as anumpy.array
. Or useininstance()
to check what type is being passed – pajton Nov 7 '11 at 13:10x<0
?x
is an array, so it is not clear what this is supposed to mean. – Björn Pollex Nov 7 '11 at 13:10