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?
0 个评论
回答(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.)
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
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!