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

1 次查看(过去 30 天)
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! :)

采纳的回答

Matt J
Matt J 2023-3-6
编辑:Matt J 2023-3-6
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 个评论

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by