Ignoring NaN in a mean only if there is a singal NaN
7 views (last 30 days)
Show older comments
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?
0 Comments
Answers (2)
Walter Roberson
on 4 Apr 2012
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.)
Geoff
on 4 Apr 2012
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 Comments
Geoff
on 4 Apr 2012
Oh, that makes that big convoluted call a bit pointless then! =) Cheers. I am probably a bit heavy-handed on arrayfun sometimes!
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!