Fill in missing NaNs
古いコメントを表示
I am trying to fill these NaNs following this rule: If there is a single NAN, I want the NAN to be filled in with the average of the numbers before and after. If there is more than one NAN. I want the NAN to be filled in with the nearest number. For example, row 2305 should be the average of 16.3 and 14.8, from 2298 to 2304 should be 16.3, and from 2306 to 2312 should be 14.8.

4 件のコメント
darova
2020 年 3 月 30 日
Do you have any code? What problem are you facing?
Cuong Nguyen
2020 年 3 月 30 日
Image Analyst
2020 年 3 月 30 日
Why not use interp1() or regionfill() to linearly interpolate from one side to the other?
Cuong Nguyen
2020 年 3 月 30 日
採用された回答
その他の回答 (2 件)
darova
2020 年 3 月 30 日
Use bwlabel
A1 = isnan(A); % find NaN
[L,n] = bwlabel(A1); % label each region
xx = 1:length(A);
for i = 1:n % loop through each region
BW = L==i; % select region
if sum(BW(:))>1 % if more than one 'NaN'
ix1 = find(BW,1,'first'); % first index of region
ix2 = floor(mean(BW.*xx)); % find mean index in region
ix3 = find(B2,1,'last'); % last index of region
A(ix1:ix2) = A(ix1-1); % fill first part
A(ix2+1:ix3) = A(ix3+1); % fill second part
else
ix = find(BW);
A(ix) = mean(A(ix([-1 1]))); % average
end
end
Andrei Bobrov
2020 年 3 月 31 日
x = [1;2;3;4;nan;nan;nan;nan;nan;5;7;8;nan;nan;nan;nan;11;11;12;nan;nan;nan;15];
out = [x,f1(x)]
x = [16.3;nan(15,1);14.8];
out = [x, f1(x)]
Here f1:
function out = f1(x)
b1 = fillmissing(x,'linear');
b2 = fillmissing(x,'nearest');
d = [0;diff(bwdist(~isnan(x)),2);0]==-2;
out = b2;
out(d) = b1(d);
end
3 件のコメント
Cuong Nguyen
2020 年 3 月 31 日
Andrei Bobrov
2020 年 3 月 31 日
No! It only says that this version is available to me :) and this code will work with R2016b and later.
Cuong Nguyen
2020 年 3 月 31 日
カテゴリ
ヘルプ センター および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
