# How to replace past vector values using future values in a while loop?

2 views (last 30 days)
Cai Chin on 19 Nov 2020
Hi, I am using MATLAB R2020a. I am trying to identify outliers from a vector in real-time based on certain conditions and then replace them with the mean of the 2 'acceptable' values on either side, i.e. one from the immediate past and one from the immediate future. Each time an acceptable value is found, it is added to a vector. I have tried doing this by replacing the outliers with zero and then once an acceptable value is found in the future, to check the previous value and if it is zero, it is replaced by the mean of the 2 framing acceptable values. However, this does not account for the fact that there may be multiple 'unacceptable' values and therefore zeros before the next 'acceptable' one. I would very much appreciate any suggestions on how to tackle this. Thanks in advance:
% Calculate exponentially weighted moving mean and tau without outliers
accepted_means = zeros(length(cycle_periods_filtered),1); % array for accepted exponentially weighted means
accepted_means(1) = cycle_periods_filtered(1);
k = zeros(length(cycle_periods_filtered),1); % array for accepted raw cycle periods
m = zeros(length(cycle_periods_filtered), 1); % array for raw periods for all cycles with outliers replaced by mean of framing values
k(1) = cycle_periods_filtered(1);
m(1) = cycle_periods_filtered(1);
tau = m/3; % pre-allocation for efficiency
i = 2; % index for counting through input signal
j = 2; % index for counting through accepted exponential mean values
n = 2; % index for counting through raw periods of all cycles
while i <= length(cycle_periods_filtered)
mavCurrent = (1 - 1/w(j))*accepted_means(j - 1) + (1/w(j))*cycle_periods_filtered(i);
if cycle_periods_filtered(i) < 1.5*(accepted_means(j - 1)) && cycle_periods_filtered(i) > 0.5*(accepted_means(j - 1)) % Identify high and low outliers
accepted_means(j) = mavCurrent;
k(j) = cycle_periods_filtered(i);
m(n) = cycle_periods_filtered(i);
cycle_index3(j) = i;
tau(n) = m(n)/3;
if m(n - 1) == 0
m(n - 1) = (k(j) + k(j - 1))/2;
tau(n - 1) = m(n)/3;
end
j = j + 1;
n = n + 1;
else
m(n) = 0;
n = n + 1;
end
i = i + 1;
end
% Scrap the tail
accepted_means(j - 1:end)=[];
tau(j - 1:end) = [];
k(j - 1:end) = [];
cycle_index3(j - 1:end) = [];