数学矩形函数 Python

Art*_*sky 1 python numpy matplotlib

我想像这样对高斯函数和矩形函数进行卷积:

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()
Run Code Online (Sandbox Code Playgroud)

但我无法正确描述 rect 函数:

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()
Run Code Online (Sandbox Code Playgroud)

tmd*_*son 5

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])
Run Code Online (Sandbox Code Playgroud)

所以你的功能可能是:

from numpy import linspace, sqrt, sin, exp, convolve, abs, where
...
def rect(x):
    return where(abs(x)<=0.5, 1, 0)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明