Azzera filtri
Azzera filtri

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

1 visualizzazione (ultimi 30 giorni)
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! :)

Risposta accettata

Matt J
Matt J il 6 Mar 2023
Modificato: Matt J il 6 Mar 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 Commenti
Matt J
Matt J il 6 Mar 2023
That shouldn't have made any difference. The 'first' flag is set internally by default.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Resizing and Reshaping Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by