Reputation: 35
I want to make convolution of gaussian and rectangular functions like that:
from numpy import linspace, sqrt, sin, exp, convolve, abs
from matplotlib import pyplot as plt
def gauss(x, x0=0, sigma=1):
return exp(-1*(x-x0)**2/(2*sigma**2))
def rect(x):
return 1 if abs(x)<=0.5 else 0
x = linspace(-10, 10, 100)
f1 = gauss(x, sigma=1)
f2 = rect(x)
fsum = convolve(f1, f2)
y = linspace(-10, 10, 199)
plt.plot(x, f1)
plt.plot(x, f2)
plt.plot(y, fsum)
plt.show()
But I can't correctly describe rect function:
return 1 if abs(x)<=0.5 else 0
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Upvotes: 2
Views: 27933
Reputation: 5
def rect(x):
y=x
for i in range(len(x)):
if abs(x[i]) <= 0.5:
y[i] = 1
else:
y[i] = 0
return y
Upvotes: -2
Reputation: 69136
Assuming you want an array of 0 and 1 values, the same shape as x
, you can use numpy.where
:
In [8]: x = np.linspace(-10, 10, 100)
In [9]: np.where(abs(x)<=0.5, 1, 0)
Out[9]:
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0])
So your function could be:
from numpy import linspace, sqrt, sin, exp, convolve, abs, where
...
def rect(x):
return where(abs(x)<=0.5, 1, 0)
Upvotes: 7