Borrar filtros
Borrar filtros

Calculate running average with NaN

7 visualizaciones (últimos 30 días)
Max Bernstein
Max Bernstein el 3 de Ag. de 2016
Comentada: Image Analyst el 4 de Ag. de 2016
Hello,
I have an array similar to array A below, but much larger:
A = [1:15;12 15 20 21 12 14 12 23 41 21 12 11 33 21 42;5 NaN NaN 42 32 42 33 22 12 NaN NaN NaN 12 42 11]';
I would like to calculate the running average of the 3rd column with a window of 4 data points and plot it overlaying on top of the original data. However, I couldnt get it to calculate the correct running average.
RA = [];
for j = 1:(length(A)-4)
RA(j,1) = mean(A(j:j+4,1));
end
figure
plot(A(:,1),A(:,2));
hold on
plot(A(:,1),A(:,3));
plot(A(:,1),RA);
How can I find the RA and overlay it on top of the old data correctly?
Thanks, Max

Respuestas (2)

Guillaume
Guillaume el 3 de Ag. de 2016
If using 2016a or later, simply:
RA = movmean(A, 5, 'omitnan', 'EndPoints', 'discard');
  1 comentario
Max Bernstein
Max Bernstein el 4 de Ag. de 2016
I dont have movmean, is there a similar script somewhere?

Iniciar sesión para comentar.


Image Analyst
Image Analyst el 3 de Ag. de 2016
Try this:
A = [1:15;12 15 20 21 12 14 12 23 41 21 12 11 33 21 42;5 NaN NaN 42 32 42 33 22 12 NaN NaN NaN 12 42 11]'
% Extract column 3 only.
col3 = A(:, 3)
% Find out where the nans are.
nanIndexes = isnan(col3)
% Turn nans into zeros
col3(nanIndexes) = 0
kernel = [1,1,1,1]; % Kernel to look at 4 elements.
% Do a running sum.
sums = conv(col3, kernel, 'valid')
% Do a running count. Count how many non-nans there are. In other words, how many good numbers.
counts = conv(double(~nanIndexes), kernel, 'valid')
% Divide them to get the means.
runningMeans = sums ./ counts
runningMeans =
23.5
37
38.6666666666667
37.25
32.25
27.25
22.3333333333333
17
12
12
27
21.6666666666667
  2 comentarios
Max Bernstein
Max Bernstein el 4 de Ag. de 2016
I had to change the 'valid' to 'same' in order to get the same array size to plot. However, this method seems to shift the magnitude of the running average down for some reason.
Image Analyst
Image Analyst el 4 de Ag. de 2016
With a window size of 4, there are 1 or 2 elements outside when the 'same' option is used. Normally the window size is odd anyway. But when the window is at the far left, about half the window will overlap the array and half will be "off" the far left end of the array. Same for the right side. You have to decide how you want to handle what's called "edge effects" which is what happens when the moving window starts to move off the main array.

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by