MATLAB Answers

## How do i average all result in total loop,if some result in some of loop are NaN

Asked by yang-En Hsiao

### yang-En Hsiao (view profile)

on 26 Mar 2019
Latest activity Answered by Jos (10584)

### Jos (10584) (view profile)

on 26 Mar 2019
Accepted Answer by Jos (10584)

### Jos (10584) (view profile)

Using matlab R2015a
I want to sum lots of numbers, and each number is the result of optimal problem in each time of loop,however in these result,some of them are NaN,if i just want to sum them,not average them,then I can just use the code below
c=0
for k=1:10
******
%optimal problem calculating code(code omit)
*******
c=c+nansum(optimal problem result)%c is the summation of all optimal problem result
end
but if I want to average these results,i mean average c, I can't just replace the "nansum" with "nanmean".because the size of optimal problem is 1 by 1 value in every loops,not a vector.so the result of nansum and nanmean will be the same.
Also,because I didn't know the amount of NaN result,so neither can I use the definition of average,total value/amount , so I want to ask if i want to average them,how do I write the code?
If you have some method ,and want to use my optimal problem calculating code to test ,please tell me,i will edit the question

#### 0 Comments

Sign in to comment.

## 1 Answer

Answer by Jos (10584)

### Jos (10584) (view profile)

on 26 Mar 2019
Accepted Answer

Store each result in an array and average after the loop. An example:
c = nan(1,10) ; % pre-allocation for speed
for k = 1:10
c(k) = function_returning_results_of_optimal_problem
end
avC = nanmean(c) % mean ignoring nans

#### 0 Comments

Sign in to comment.