mean value of a group of data with NaNs

조회 수: 3 (최근 30일)
Leon
Leon 2016년 6월 27일
댓글: the cyclist 2016년 6월 28일
I have a matrix A with the dimension of 12x360x180. It stores 12 values at each grid of the 360x180. Now I want to calculate the average value at each grid point. The problem is that there are unknown number of NaNs. Sometimes all 12 values are non-NaNs, sometimes all of them are NaNs, sometimes a portion of the 12 values are NaNs.
In this case, how do I estimate the mean values at each point of the grid? I know if there are no NaNs, the calculation is as easy as B = mean(A);
Thank you.

채택된 답변

the cyclist
the cyclist 2016년 6월 27일
편집: the cyclist 2016년 6월 27일
If you have the Statistics and Machine Learning Toolbox, you can use the nanmean function, which computes the mean while ignoring NaNs.
  댓글 수: 1
Leon
Leon 2016년 6월 27일
편집: Leon 2016년 6월 27일
Many thanks! It works very well!
I happen to have Statistics toolbox on my version of the Matlab :-)

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Chris Turnes
Chris Turnes 2016년 6월 27일
You can also just use the 'omitnan' option in "mean":
A = [1 0 0 1 NaN 1 NaN 0];
M = mean(A,'omitnan')
M =
0.5000
  댓글 수: 3
Chris Turnes
Chris Turnes 2016년 6월 27일
By the way, other related functions support this input argument as well: sum, var, std, median, and max and min (max and min have 'omitnan' as the default option). The mov* functions (if you have R2016a or newer) also support this argument.
the cyclist
the cyclist 2016년 6월 28일
I was unaware of this option! Very nice. Please accept my upvote.

댓글을 달려면 로그인하십시오.


the cyclist
the cyclist 2016년 6월 27일
If you do not have that Statistics and Machine Learning Toolbox, this should work:
notNan = not(isnan(A));
B = zeros(size(A));
B(notNan) = A(notNan);
sum(B)./sum(notNan)
You can do the sum over different dimensions, as required.
  댓글 수: 1
Leon
Leon 2016년 6월 27일
편집: Leon 2016년 6월 27일
Brilliant! Good to have this alternative method for folks who do not have the Statistic toolbox and come to this page through search engine.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Descriptive Statistics and Visualization에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by