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?

Antworten (4)

KSSV
KSSV am 10 Aug. 2021
Bearbeitet: KSSV am 10 Aug. 2021

1 Stimme

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
Wan Ji am 10 Aug. 2021

1 Stimme

It is convenient to use fillmissing function to get what you want
matOut = fillmissing(matrixIn, 'linear', 'EndValues','nearest')

4 Kommentare

Konvictus177
Konvictus177 am 10 Aug. 2021
What if an entrie column is NaN?
Wan Ji
Wan Ji am 10 Aug. 2021
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
Yazan am 10 Aug. 2021
This does linear interpolation of neighboring non-nan values. It does not replace nan values with the median.
Wan Ji
Wan Ji am 10 Aug. 2021

Melden Sie sich an, um zu kommentieren.

Stephen23
Stephen23 am 10 Aug. 2021
Bearbeitet: Stephen23 am 10 Aug. 2021

1 Stimme

M = randi(3,5,7);
M(randi(numel(M),1,9)) = NaN
M = 5×7
1 NaN 1 1 2 3 1 NaN 1 2 NaN 1 1 3 NaN 3 NaN 1 2 1 NaN 2 NaN 3 2 3 2 2 1 1 2 NaN 1 3 2
V = median(M,1,'omitnan')
V = 1×7
1 1 2 1 2 2 2
X = isnan(M);
M(X) = repelem(V,sum(X,1))
M = 5×7
1 1 1 1 2 3 1 1 1 2 1 1 1 3 1 3 2 1 2 1 2 2 1 3 2 3 2 2 1 1 2 1 1 3 2
Yazan
Yazan am 10 Aug. 2021

1 Stimme

clc, clear
x1 = randn(5, 5);
x1(randi(numel(x1), 1, 5)) = nan;
x2 = fillmissing(x1, 'movmedian', size(x1,1)*2, 1);
display(x1)
x1 = 5×5
NaN 0.1826 NaN 0.3875 -0.7928 1.3983 -0.1527 0.1261 0.1482 -0.8491 1.4623 0.7005 -0.0511 -0.1259 1.1562 0.8948 0.0311 0.0064 NaN NaN -0.2615 -0.1371 -1.7245 0.9723 0.5918
display(x2)
x2 = 5×5
1.1466 0.1826 -0.0223 0.3875 -0.7928 1.3983 -0.1527 0.1261 0.1482 -0.8491 1.4623 0.7005 -0.0511 -0.1259 1.1562 0.8948 0.0311 0.0064 0.2678 -0.1005 -0.2615 -0.1371 -1.7245 0.9723 0.5918

Gefragt:

am 10 Aug. 2021

Beantwortet:

am 10 Aug. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by