How to fill zeros and NaNs with the average of the previous nonzero consecutive values

1 visualización (últimos 30 días)
Hi fellow helpers!
So, i have a column like this:
T = [0;0;1;2;3;4;NaN;4;3;0;0;0;NaN;4;2;3;0;2;0];
And everytime I have a NaN or a zero, I would like to transform them in the average of the previous nonzero consecutive values (averages in bold):
T = [0;0;1;2;3;4;2.5;4;3;3.5;3.5;3.5;3.5;4;2;3;3;2;2];
I cannot figure out how I can do this in an efficient way (without for loops, because the column has thousands of rows).
I hope you can help me out! Thanks! :)

Respuesta aceptada

Matt J
Matt J el 6 de Mzo. de 2023
Editada: Matt J el 6 de Mzo. de 2023
Using this FEX download,
T = [0;0;1;2;3;4;NaN;4;3;0;0;0;NaN;4;2;3;0;2;0];
idx=find(T,1);
[stem,T]=deal(T(1:idx-1),T(idx:end));
G=groupTrue(~isnan(T) & T~=0);
[~,~,lengths]=groupLims(groupTrue(~G),1);
T(~G)=repelem( groupFcn(@mean,T,G) ,lengths);
T=[stem;T]
T'
ans =
Columns 1 through 9
0 0 1.0000 2.0000 3.0000 4.0000 2.5000 4.0000 3.0000
Columns 10 through 18
3.5000 3.5000 3.5000 3.5000 4.0000 2.0000 3.0000 3.0000 2.0000
Column 19
2.0000
  3 comentarios
Matt J
Matt J el 6 de Mzo. de 2023
That shouldn't have made any difference. The 'first' flag is set internally by default.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

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

Community Treasure Hunt

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

Start Hunting!

Translated by