# MATLAB: How to calculate an exponentially weighted moving average on a conditional basis

exponential weightingMATLABmoving meansignal processingstatistics

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.

``%Let t be a 1-D array of data pointslambda = 0.1; %forgetting factorprevWeightFactor = 0; %initialise weight factor and moving averageprevAvg = 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;    endend``