Averaging Every 5 Elements in a Matrix for Each Column with Nans

1 回表示 (過去 30 日間)
Josh
Josh 2020 年 5 月 10 日
コメント済み: Josh 2020 年 5 月 11 日
I have a matrix of 2241x6914 and I was hoping to average every 5th element of each column such that the final matrix is 448x6914. The issue is that there are locations in which Nans appear in the data and I dont want these to affect this averaging. Ive tried the below code and it generally works but im curious if there is any way for it to not cause a Nan to default the average of the 5 elements to NaN. What I mean by this is that if the values [1,2,3,Nan,4] were being averaged, the value would return Nan as opposed to the 2.5 I would want. Is there any ways around this? I'll also note that im sure this isnt the most efficient way to code this but it just was the most simple way in my eyes. Any help would be appreciated!
Ch3StrainAvg(1,:)=ChtrainData(1,:);
endCondition=size(Ch3StrainData,1)-4
n=2
for j=2:5:endCondition
Ch3StrainAvg(n,:)=((Ch3StrainData(j,:)+Ch3StrainData(j+1,:)+Ch3StrainData(j+2,:)+Ch3StrainData(j+3,:)+Ch3StrainData(j+4,:))/5);
n=n+1;
end

採用された回答

Toder
Toder 2020 年 5 月 10 日
For x=[1 2 3 NaN 4], like your short example, you can do this to ignore NaNs in the mean:
mean(x(~isnan(x)))
  5 件のコメント
Toder
Toder 2020 年 5 月 11 日
Sure thing. Do you mind accepting my answer?
Josh
Josh 2020 年 5 月 11 日
Done!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by