Filter löschen
Filter löschen

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

1 Ansicht (letzte 30 Tage)
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! :)

Akzeptierte Antwort

Matt J
Matt J am 6 Mär. 2023
Bearbeitet: Matt J am 6 Mär. 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 Kommentare
Matt J
Matt J am 6 Mär. 2023
That shouldn't have made any difference. The 'first' flag is set internally by default.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by