필터 지우기
필터 지우기

How to replace NaN with column mean if less than b NaN in a column?

조회 수: 1 (최근 30일)
Katerina F
Katerina F 2014년 10월 20일
댓글: Katerina F 2014년 10월 22일
Hello, Say I have the martix:
MA=[1 2 3 NaN; 6 NaN NaN 9; NaN NaN NaN 9;NaN 45 NaN 9;NaN NaN NaN 19;1 12 3 34] I would like to replace the NaNs in each column with the average of the column if the number of NaNs in the column is less than 4. Any easy way to do this please? I know that to find the average of the column I can use the nanmean function. Note that the actual matrices that I have are much larger, but I know the total number of rows and columns.
thanks, K

채택된 답변

Andrei Bobrov
Andrei Bobrov 2014년 10월 20일
편집: Andrei Bobrov 2014년 10월 21일
n = nanmean(MA);
nn = isnan(MA);
ii = sum(nn) < 4;
z = MA(:,ii);
z(nn(:,ii)) = nonzeros(bsxfun(@times,nn(:,ii),n(ii)));
MA(:,ii) = z;
or
n = nanmean(MA);
nn = isnan(MA);
ii = bsxfun(@and,nn,sum(nn) < 4);
MA(ii) = n(nonzeros(bsxfun(@times,ii,1:numel(n))));
or
n = nanmean(MA);
nn = isnan(MA);
ii = bsxfun(@and,nn,sum(nn) < 4);
[~,idx] = find(ii);
MA(ii) = n(idx);
  댓글 수: 3
Katerina F
Katerina F 2014년 10월 22일
Thank you very much Andrei, it works fine. K.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by