1 功能介绍
CANape的Function自带Moving_Average,可以求该时刻点前连续n个点的平均值,原理图如下:
2 源程序
为方便理解,转化为Python代码:
"""
名称: Data_Average_4_Points.py
作者: Morven_Xie
版本: 1.0
时间: 2020/8/29 22:50
功能: 用于求取信号平均值
简介: 滑动平均值,求某个点所在位置的前n个点均值
Email: morven_xie@163.com
"""
#coding=utf-8
from matplotlib import pyplot as plt #用于作图
list = [0.5, 1.5, 8, 3.5, 4.5, 2, 6.5, 4, 8.5, 6, 3.5, 6.5, 8, 1.5, 5.5, 0, 6.5, 8, 8.5, 6]
first = 1
index = 0
times = 4
t = []
lastvalue = []
average_list = []
for i in range(0,len(list)):
t.append(i) # 生成时间轴坐标
for j in range(0, len(list)): # 遍历列表list中所有点
if(first):
first = 0 # first=0为假
sum=times*list[0] # 首次运行sum =times*第一个点
for k in range(0, times):
lastvalue.append(list[0]) # lastvalue列表赋值
print(lastvalue)
sum-=lastvalue[index] # sum减最后一个数值
sum+=list[j] # sun加最新数值
lastvalue[index]=list[j] # 将最新list数值周期性赋值给 lastvalue [index]
index+=1 # index周期性赋值
if (index >=times):
index=0
average=sum / times # 求均值
average_list.append(average) # 将均值构成列表 average list
fig,ax=plt.subplots() # 作图,等价fig = plt.figure();ax = fig.add_subplot(1,1,1)
plt.plot(t, list, label='list') # 使用 pyplot作图,图例为list
plt.plot(t, average_list, label='average_list') # 使用 pyplot作图,图例为average_list
ax.set_title('Average 4 Points') # 图表表头
ax.legend (loc='upper left') # 显示图例位置,plt. legend0,左上
plt.savefig('Average_4_Points', dpi=100) # 保存图片文件到文件夹
plt.show()
运行结果:
留意,前三个点的数据趋势是对的,但是值有差距。