Share trajectory smoothing algorithm moving average smoothing (Moving Average, MA) MATLAB code

application

Used for one-dimensional, two-dimensional, and three-dimensional trajectory smoothing (use this function for the axis that needs to be smoothed)

official

以 5 点 MA 平滑 为例 :
ys (i) = 1 2 N + 1 (y (i + N) + y (i + N - 1) +… + y (i - N)) ys (1) = y (1) ys (2) = (y (1) + y (2) + y (3)) / 3 ys (3) = (y (1) + y (2) + y (3) + y (4 ) + y (5)) / 5 ys (4) = (y (2) + y (3) + y (4) + y (5) + y (6)) / 5 \ begin {array} {l} y_ {s} (i) = \ frac {1} {2 N + 1} (y (i + N) + y (i + N-1) + \ ldots + y (iN)) \\ y_ {s} (1) = y (1) \\ y_ {s} (2) = (y (1) + y (2) + y (3)) / 3 \\ y_ {s} (3) = (y (1 ) + y (2) + y (3) + y (4) + y (5)) / 5 \\ y_ {s} (4) = (y (2) + y (3) + y (4) + y (5) + y (6)) / 5 \ end {array}ands(i)=2 N + 11(y(i+N)+y(i+N1)++y(iN))ands(1)=and ( 1 )ands(2)=( and ( 1 )+and ( 2 )+and ( 3 ) ) / 3ands(3)=( and ( 1 )+and ( 2 )+and ( 3 )+and ( 4 )+and ( 5 ) ) / 5ands(4)=( and ( 2 )+and ( 3 )+and ( 4 )+and ( 5 )+and ( 6 ) ) / 5

MATLAB functions

function res = MovingAverage(input,N)
%% input为平滑前序列(列向量和行向量均可);N为平滑点数(奇数);res返回平滑后的序列(默认行向量)。
sz = max(size(input));
n = (N-1)/2;
res = [];
for i = 1:length(input)
    if i <= n
        res(i) = sum(input(1:2*i-1))/(2*i-1);
    elseif i < length(input)-n+1
        res(i) = sum(input(i-n:i+n))/(2*n+1);
    else
        temp = length(input)-i+1;
        res(i) = sum(input(end-(2*temp-1)+1:end))/(2*temp-1);
    end
end
end

Input is the sequence before smoothing (both column vector and row vector are both); N is the number of smoothing points (odd number); res returns the smoothed sequence.

one example

clear;clc;close all;
arr = [1,2,4,3,6,5,7,7,9,10];
plot(1:10,arr,'LineWidth',3,'color','r');hold on;
arr_MA = MovingAverage(arr, 5);
plot(1:10,arr_MA,'LineWidth',3,'color','b')
legend("平滑前","平滑后");grid on;

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43145941/article/details/114178281