I have a problem with use if
and else
statement in convolution function.
this code return error:
use any() or all()
JavaScript
x
20
20
1
import matplotlib.pyplot as plt
2
import numpy as np
3
4
def name(y):
5
if y<300 :
6
print("if")
7
fun2=y-6
8
return fun2
9
else:
10
fun2=6-y
11
print("else")
12
return fun2
13
14
y=np.arange(1,1000,1)
15
x=np.arange(1,1000,1)
16
fun1=np.sin(x)
17
con=np.convolve(fun1,name(y))
18
plt.plot(con)
19
plt.show()
20
how to can i use condition in convolve?
I hope you always good luck. thanks.
Advertisement
Answer
The name
function is called with a numpy array as the parameter. “Is the array less than 300?” isn’t meaningful. Are all the items less than 300, np.all
? Are any of them less than 300, np.any
?
My guess is that you want something like:
JavaScript
1
10
10
1
def name( y ):
2
sign = 1 - 2*(y>300)
3
return sign * (y-6)
4
5
y = np.arange( 290, 310 )
6
name( y )
7
8
# array([ 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294,
9
# -295, -296, -297, -298, -299, -300, -301, -302, -303])
10
This uses the boolean result for each item in the array to perform arithmetic and is one way of allowing different treatments for different elements in an array.