필터 지우기
필터 지우기

how to calcuate mean with NaN

조회 수: 4 (최근 30일)
Peihong
Peihong 2013년 9월 12일
댓글: Esen S. 2020년 4월 21일
Dear Friend,
There are two matrixs with the same size, there are some NaNs in each matrix. I want to calculate the mean of corresponding datapoints, which might contain NaN. for example, A(1,2)=NaN, B(1,2)=3, I need the average of the sum of 3+NaN divided by the effective number of data points, here is 1 since A(1,2) is NaN, to be 3. If A(2,2)=2,B(2,2)=5, I need the average to be (2+5)divided by 2, which equals 3.5 since neither A(2,2) and B(2,2) contains NaN. Is there a way to achieve this goal without using a for loop? thanks

채택된 답변

Sven
Sven 2013년 9월 12일
편집: Sven 2013년 9월 12일
If you have the Statistics Toolbox, just replace calls to mean() with calls to nanmean().
If you don't have it, you can do the same by downloading the File Exchange contribution nansuite
Here's an example:
A = reshape(1:4,2,2);
B = A + 10;
A([1 3]) = nan % Set some NaNs
B([1 2]) = nan
yourMean = nanmean(cat(3,A,B),3)
Which results in:
A =
NaN NaN
2 4
B =
NaN 13
NaN 14
yourMean =
NaN 13
2 9
  댓글 수: 1
Peihong
Peihong 2013년 9월 12일
Hi, Sven, thanks a lot. It's exactly what I need.

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

추가 답변 (2개)

Jan
Jan 2013년 9월 12일
Emulating NANMEAN without the statistics toolbox is easy:
index = isnan(X);
X(index) = 0;
M = sum(X, 2) ./ sum(index, 2);
  댓글 수: 1
Esen S.
Esen S. 2020년 4월 21일
I belive there is a tilde missing in the last line.
It should be M = sum(X, 2) ./ sum(~index, 2);

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


Shashank Prasanna
Shashank Prasanna 2013년 9월 12일

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by