How to remove all NaN and Inf values when calculate the mean?

조회 수: 33 (최근 30일)
Amy
Amy 대략 22시간 전
편집: Matt J 대략 20시간 전
I just computed a 167*50 double matrix (Log_ret) mean, with a lot of NaN and +-Inf. I've seen a solution from another question, which is really good. But when I got the extractedData, all the data turn into one column, which means that I got a 6798*1 double variable. So, how can I keep the reult still in their previous column without moving in to one column. (I mean numbers in column 2 after removing all NaN and Inf still in the column2 and column 33 after removing all NaN and Inf still in the column 33 etc.)
Thanks in advance!
mask = (Log_ret ~= 0) & isfinite(Log_ret)
extractedData = Log_ret(mask)
  댓글 수: 1
the cyclist
the cyclist 대략 21시간 전
To take a smaller example, suppose Log_ret is
Log_ret = [ 2 3 Inf;
NaN 5 7]
What do want the output extractedData to be? Be specific. There is no such thing as an "empty" slot in a numeric array.

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

답변 (1개)

Matt J
Matt J 대략 21시간 전
편집: Matt J 대략 21시간 전
If you're saying you want to take the column-wise mean, ignoring zeros and non-finite values, then you could do,
exclude = (Log_ret == 0) | ~isfinite(Log_ret) ;
extractedData=Log_ret;
extractedData(exclude)=nan;
columnMeans = mean(extractedData,1,'omitnan'); %the result
In other words, you shouldn't approach it by trying to remove NaNs and Infs. You should approach it by converting all values you want to exclude to NaNs and using the omitnan flag, where appropriate.
  댓글 수: 2
Les Beckham
Les Beckham 대략 21시간 전
I'm wondering why you are excluding the zero elements. Doing that will change the mean values. I don't see anything in OP's question about excluding zeros, just +/- Inf and NaN.
Matt J
Matt J 대략 20시간 전
편집: Matt J 대략 20시간 전
In the OP's code, we see zeros are excluded,
(Log_ret ~= 0)

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by