I have a column in which some values are missing and shown as NaN. I need to replace all these NaN with the median of the column. Here is what I tried: I am extracting column 4 in which there are missing values, find the median value, Use isnan to replace the logical 1 with the median.
Column 4 values: 1 2 3 4 5 6 NaN 12 10 NaN 4 5 NaN
C=num(:,4);
median=nanmedian(C);
R(isnan(C))=median;
But with this I am getting results as : 0 0 0 0 0 0 12 0 0 12 0 0 12
But the expected result is: 1 2 3 4 5 6 12 12 10 12 4 5 12
Any suggestions ?

 채택된 답변

Star Strider
Star Strider 2017년 6월 21일

0 개 추천

Please do not use ‘median’ as a variable name.
I don’t know where the ‘12’ value comes from, since the median of the vector you posted is 4.5.
Other than that, ‘R’ does not magickally become ‘C’. You have to create it first.
This works for me:
C = [1 2 3 4 5 6 NaN 12 10 NaN 4 5 NaN]';
median_4 = nanmedian(C);
R = C;
R(isnan(C)) = median_4;

댓글 수: 2

Daphne Mariaravi
Daphne Mariaravi 2017년 6월 21일
The median value 12 wasn't actually calculated. I just filled in some random values just to give a picture of what my problem was. Sorry about that. The code works! Thanks
Star Strider
Star Strider 2017년 6월 21일
My pleasure!

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

추가 답변 (1개)

Steven Lord
Steven Lord 2017년 6월 21일

0 개 추천

If you're using release R2016b or later use fillmissing.
z = [1 2 3 4 5 6 NaN 12 10 NaN 4 5 NaN].';
y = fillmissing(z, 'constant', median(z, 'omitnan'));
showBothColumnsSideBySide = [z, y]

댓글 수: 3

Daphne Mariaravi
Daphne Mariaravi 2017년 6월 21일
@stevenLord using the fillmissing I am getting the following error "Subscript indices must either be real positive integers or logicals."
Jan
Jan 2017년 6월 21일
@Daphne: This happens, because "median" was defined as a variable on your computer. Do not shadow builtin functions by variables. Solution: Restart Matlab or:
clear median
Daphne Mariaravi
Daphne Mariaravi 2017년 6월 21일
Yes. Got it! Thank you

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

카테고리

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

질문:

2017년 6월 21일

댓글:

2017년 6월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by