## 2021年10月18日13:14:28 完成
def smooth2nd(x,M): ##x 为一维数组
K = round(M/2-0.1) ##M应为奇数,如果是偶数,则取大1的奇数
lenX = len(x)
if lenX<2*K+1:
print('数据长度小于平滑点数')
else:
y = np.zeros(lenX)
for NN in range(0,lenX,1):
startInd = max([0,NN-K])
endInd = min(NN+K+1,lenX)
y[NN] = np.mean(x[startInd:endInd])
## y[0]=x[0] #首部保持一致
## y[-1]=x[-1] #尾部也保持一致
return(y)
######################################################################
## 测试程序
if __name__ == '__main__':
import numpy as np
import matplotlib.pyplot as plt
mngr = plt.get_current_fig_manager()
## mngr.window.wm_geometry("+70+0") # 调整窗口在屏幕上弹出的位置
x = np.random.randn(100,1) ##产生随机数
M=5 ## 做 M点平滑, M为奇数
y=smooth2nd(x,M)
## 画图展示
plt.plot(x,c='b')
plt.plot(y,c='r')
plt.show()
python 平滑函数 smooth
于 2021-10-18 17:08:44 首次发布
这段代码定义了一个名为`smooth2nd`的函数,用于对一维数组进行数据平滑处理。它采用中值滤波的方式,通过计算指定窗口大小内的数据平均值来实现平滑效果。当输入数据长度小于平滑点数时,函数会给出提示。在测试程序中,生成了一组随机数并应用了5点平滑,最后用红色线条展示了平滑后的结果。
1535

被折叠的 条评论
为什么被折叠?



