Ignoring NaN in a mean only if there is a singal NaN

1 次查看(过去 30 天)
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
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.)

Geoff
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 个评论
Geoff
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!

请先登录,再进行评论。

类别

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