Replace NaN with median per column
古いコメントを表示
Hi,
I have a matrix where I have NaN values in a few columns.
I would like to fill the NaN values with the median value of that column. How do I do that?

回答 (4 件)
Read about fillmissing.
Or USe:
A = rand(20,1) ; % data for demo
A(randperm(20,5)) = NaN ; % insert nans
M = nanmedian(A) ; % get median
A(isnan(A)) = M % replace nans with medians
Wan Ji
2021 年 8 月 10 日
It is convenient to use fillmissing function to get what you want
matOut = fillmissing(matrixIn, 'linear', 'EndValues','nearest')
4 件のコメント
Konvictus177
2021 年 8 月 10 日
Wan Ji
2021 年 8 月 10 日
if a whole NaN column exists, you can transpose the matrix and use the above method. btw, meaningless if a column is all NaN, isn't it?
Yazan
2021 年 8 月 10 日
This does linear interpolation of neighboring non-nan values. It does not replace nan values with the median.
Wan Ji
2021 年 8 月 10 日
M = randi(3,5,7);
M(randi(numel(M),1,9)) = NaN
V = median(M,1,'omitnan')
X = isnan(M);
M(X) = repelem(V,sum(X,1))
clc, clear
x1 = randn(5, 5);
x1(randi(numel(x1), 1, 5)) = nan;
x2 = fillmissing(x1, 'movmedian', size(x1,1)*2, 1);
display(x1)
display(x2)
カテゴリ
ヘルプ センター および File Exchange で NaNs についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!