Replace NaN values with median for each row

Hi guys,
I have this table:
Date var_1 var_2 var_3 var_4 var_5 var_6
01-01-90 0.2 0.34 0.43 0.12 0.18 0.1
01-01-91 0.3 0.54 0.53 0.62 0.38 0.2
01-01-92 0.7 0.40 0.77 0.42 NaN 0.2
01-01-93 0.7 0.40 0.77 0.42 NaN 0.2
How do I replace the NaN values in the table with the median of the row for each row?
The result for this table should be:
Date var_1 var_2 var_3 var_4 var_5 var_6
01-01-90 0.2 0.34 0.43 0.12 0.18 0.1
01-01-91 0.3 0.54 0.53 0.62 0.38 0.2
01-01-92 0.7 0.40 0.77 0.42 Med_Row 0.2
01-01-93 0.7 0.40 0.77 0.42 Med_Row 0.2

 채택된 답변

madhan ravi
madhan ravi 2020년 7월 9일
편집: madhan ravi 2020년 7월 9일

0 개 추천

m = TablE{:,2:end};
ix = any(isnan(m),2);
mix = m(ix,:);
m1 = median(m(ix,:),2,'omitnan') .* isnan(m(ix,:))
m1(m1==0) = mix(~isnan(mix));
m(ix,:) = m1
TablE{:,2:end} = m

댓글 수: 5

gcicceri
gcicceri 2020년 7월 9일
what if there are more Nan values in the row?
madhan ravi
madhan ravi 2020년 7월 9일
See edited answer.
gcicceri
gcicceri 2020년 7월 9일
Thanks, could you write the comments for each line code to understand all the steps?
madhan ravi
madhan ravi 2020년 7월 9일
편집: madhan ravi 2020년 7월 9일
1) converting table to a matrix
2) detecting which rows of matrix has nans in it
3) saving those twos of matrix in a variable called mix
4) calculating median for those rows and assigning it to the matrix where nana occurs
5) copying the values other than nan
6) replacing those rows to the original matrix
7) converting it back to a table
gcicceri
gcicceri 2020년 7월 9일
Perfect. thanks

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Data Preprocessing에 대해 자세히 알아보기

질문:

2020년 7월 9일

댓글:

2020년 7월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by