Effacer les filtres
Effacer les filtres

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

2 vues (au cours des 30 derniers jours)
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! :)

Réponse acceptée

Matt J
Matt J le 6 Mar 2023
Modifié(e) : Matt J le 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 commentaires
Matt J
Matt J le 6 Mar 2023
That shouldn't have made any difference. The 'first' flag is set internally by default.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by