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

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 日

1 投票

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 月 20 日
Thanks, this seems nice, because there is no loop, but in a slightly different case it gives me a strange result: Say: MA=[1 2 NaN NaN; 6 NaN NaN 9;4 NaN NaN 9;NaN 45 NaN 9;5 NaN NaN 19;NaN 12 NaN 34], which is: MA =
1 2 NaN NaN
6 NaN NaN 9
4 NaN NaN 9
NaN 45 NaN 9
5 NaN NaN 19
NaN 12 NaN 34
then, the result is: MA =
1.0000 2.0000 16.0000 NaN
6.0000 19.6667 NaN 9.0000
4.0000 19.6667 NaN 9.0000
4.0000 45.0000 NaN 9.0000
5.0000 19.6667 NaN 19.0000
4.0000 12.0000 NaN 34.0000
_
Andrei Bobrov
Andrei Bobrov 2014 年 10 月 21 日
corrected
Katerina F
Katerina F 2014 年 10 月 22 日
Thank you very much Andrei, it works fine. K.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

質問済み:

2014 年 10 月 20 日

コメント済み:

2014 年 10 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by