MATLAB Answers

How to calculate an exponentially weighted moving average on a conditional basis?

157 views (last 30 days)
Cai Chin
Cai Chin on 9 Nov 2020
Commented: Cai Chin on 14 Nov 2020
Hi, I am using MATLAB R2020a on a MacOS. I have a signal 'cycle_periods' consisting of the cycle periods of an ECG signal on which I would like to perform an exponentially weighted mean, such that older values are less weighted than newer ones. However, I would like this to be done on an element-by-element basis such that a given element is only included in the overall weighted mean if the weighted mean with the current sample does not exceed 1.5 times or go below 0.5 times the weighted mean without the element.
I have used the dsp.MovingAverage function as shown below to calculate the weighted mean, but I am really unsure as to how to manipulate the function to include my conditions.
% Exponentially weighted moving mean for stable cycle periods
movavgExp = dsp.MovingAverage('Method', 'Exponential weighting', 'ForgettingFactor', 0.1);
mean_cycle_period_exp = movavgExp(cycle_periods);
I would very much appreciate any help regarding this matter, thanks in advance.
  1 Comment
Mathieu NOE
Mathieu NOE on 10 Nov 2020
your special case is not covered in the standard matlab package
you will have to create your own , but that doesn't seems a "mission impossible"
all the best

Sign in to comment.

Accepted Answer

Uday Pradhan
Uday Pradhan on 12 Nov 2020
Edited: Uday Pradhan on 12 Nov 2020
Hi Cai,
In order to accomodate your custom conditions, you may think about creating a small script to mimic the algorithm used by the dsp.MovingAverage system object (exponential wieghing method). A very detailed explanation about the same is given in this link. I have created a dummy code for reference:
%Let t be a 1-D array of data points
lambda = 0.1; %forgetting factor
prevWeightFactor = 0; %initialise weight factor and moving average
prevAvg = 0;
for i = 1 : length(t)
presentWeightFactor = lambda * prevWeightFactor + 1;
presentAvg = (1 - (1/presentWeightFactor)) * prevAvg + (1/presentWeightFactor) * t(i);
if (presentAvg < 0.5 * prevAvg) || (presentAvg > 1.5 * prevAvg)
presentAvg = prevAvg; %ignore this input, you might want to skip this step for the first sample
else %accept this input in the moving average
prevWeightFactor = presentWeightFactor;
prevAvg = presentAvg;
I hope this helps!
Cai Chin
Cai Chin on 14 Nov 2020
Hi Uday, this makes so much sense now, I have removed the erroneously small values and the result is now what I wanted. Thank you very much for all your help!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!