Ignoring NaN in a mean only if there is a singal NaN
이전 댓글 표시
I would like to determine the mean of a set of cells in a matrix but I would like to have the mean be an NaN if there is more than one NaN value in the original data set.
for example if x = [2 NaN 4] then the mean would be 3 if x = [2 NaN NaN] then the mean would be NaN
so far I have been using
nanmean(x(:,1:3),2)
Is there a logical string I could use that would allow me to only ignore the NaN if there was a single NaN in the row?
답변 (2개)
Walter Roberson
2012년 4월 4일
One liner:
nanmean(x,2) + 0 ./ (sum(isnan(x),2) < 2)
I suggest you work through it to figure out how it works: it is not obvious (except perhaps to old-timers.)
댓글 수: 1
Oleg Komarov
2012년 4월 4일
I always forget the trick 0/0.
Geoff
2012년 4월 4일
Compute the mean with nanmean as usual, and then check for multiple NaNs:
You can count the NaN values in an array like so:
sum(isnan(x))
But you want to do this on a row basis. How about this:
means = nanmean(x, 2);
bad = arrayfun( @(row) sum(isnan(x(row,:))) > 1, 1:size(x,1) );
means(bad) = NaN;
댓글 수: 2
Oleg Komarov
2012년 4월 4일
sum(isnan(x),2) to sum along columns
Geoff
2012년 4월 4일
Oh, that makes that big convoluted call a bit pointless then! =) Cheers. I am probably a bit heavy-handed on arrayfun sometimes!
카테고리
도움말 센터 및 File Exchange에서 NaNs에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!