To find the average when there is NaN

3 ビュー (過去 30 日間)
Thishan Dharshana Karandana Gamalathge
コメント済み: Walter Roberson 2017 年 8 月 18 日
I want to find the average of each pairs. ie. avg of 2 &4, avg of NaN and 5. Answer should be 3 and 5. For the second pair, code should eliminate NaN, so avg should be 5. That's where I have the problem. Following is the code I wrote. Thanks.
A=[2 4 NaN 5];
j=1;
for i=1:2:4
B=A(i:i+1);
C=~isnan(B);
test(j)=mean(A(C));
i=i+1;
j=j+1;
end

回答 (2 件)

Chad Greene
Chad Greene 2017 年 8 月 17 日
編集済み: Chad Greene 2017 年 8 月 17 日
Hi Thishan,
On newer versions of Matlab, use
test(j)=mean(A(C),'omitnan');
If you have an older version of Matlab and you have the Statistics Toolbox, use
test(j)=nanmean(A(C));
Alternatively, if neither of those options work for you,
tmp = A(C);
test(j)= = mean(tmp(isfinite(tmp)));
  7 件のコメント
Image Analyst
Image Analyst 2017 年 8 月 17 日
Sure it makes sense. You can move along the vector an element at a time taking the means of pairs, no matter whether there are an odd or even number of elements. Just look:
m = [1,2,3,4,5]
pairMeans = conv(m, [.5,.5], 'valid')
m =
1 2 3 4 5
pairMeans =
1.5 2.5 3.5 4.5
(Note the above does not handle nans in the desired way).
Walter Roberson
Walter Roberson 2017 年 8 月 18 日
However, the user's for loop increments by 2, so that is not the pairs they meant. They also indicated they expected exactly 2 results, not 3.

サインインしてコメントする。


Image Analyst
Image Analyst 2017 年 8 月 17 日
編集済み: Image Analyst 2017 年 8 月 17 日
This will work for any length of A, even odd numbers:
A=[2 4 NaN 5 6 8 9]; % 7 elements.
kernel = [1,1];
sumA = conv(A, kernel, 'same')
nonNaNA = ~isnan(A)
denom = conv(nonNaNA, kernel, 'same')
output = sumA ./ denom
output(isnan(output)) = [] % Remove nans.

カテゴリ

Help Center および File ExchangeCorrelation and Convolution についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by