Can we sum a series of values,even some of them are "NaN"?If i want to do it,how can i do?

조회 수: 1 (최근 30일)
I get a series answer of optimal problem in several times,and i want to sum of them and average them,however, some of them are "NaN",can i or how to write a code to ignore those "NaN" and sum the others which is not "NaN" ?
The version of matlab is 2015a

채택된 답변

Walter Roberson
Walter Roberson 2019년 3월 26일
You did not indicate your MATLAB version.
For a couple of years now, you have been able to write sum(TheArray, 'omitnan') .
Before that, the easiest approach was to use the Statistics toolbox nansum()
mean() these days also has 'omitnan' flag, and in older versions the Stats tool was nanmean()
  댓글 수: 2
yang-En Hsiao
yang-En Hsiao 2019년 3월 26일
편집: yang-En Hsiao 2019년 3월 26일
Thanks for information,i have edited the question,if there is a vector call A
A=[1 2 3 4 5 6 7 8 9 NaN]
ANSwess=nansum(A)
The window will show me ANSwess=45,but why when i write the code as
A=[1 2 3 4 5 6 7 8 9 NaN]
ANSwess=nansum(A(1:9)+A(end))
The window will show me ANSwess=45,same result as sum(A)?
Walter Roberson
Walter Roberson 2019년 3월 26일
That last line returns 0 for me. A(end) is Nan, and adding nan to each A(1:9) entry gives nan for each result, so you would be applying nansum to an all-nan vector, and the result of that is going to be 0.

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

추가 답변 (0개)

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by