I have a pretty tricky problem that I can't seem to solve. The basic problem can be expressed as follows:

- I have a stream of data (in my example code below its expressed as a loop where the data is just the values 1 -> 20.

- I want to calculate the mean and standard deviation at each iteration of the loop, but only for the last five values.

- Normally for a running mean and std dev I would do something like:

Code:

```
for ( i = 0 ; i < 20 ; ++i )
{
data = (i+1) ;
temp = mean ;
mean += (data - mean) / (i+1) ;
svar += (data - temp) * (data - mean) ;
stdd = sqrt(svar/(i+1)) ;
}
```

Code:

```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
/* variables to keep statistics data */
double * data ;
double mean ;
double stdd ;
double sum ;
/* number of frames needed to get a mean and standard deviation */
int frames_needed ;
/* elements to index data array */
int new_index ;
int old_index ;
int i, j ;
/* initialise variables */
frames_needed = 5 ;
data = (double *) malloc((frames_needed) * sizeof(double)) ;
sum = new_index = old_index = 0 ;
old_index = -1 ;
for ( i = 0 ; i < 20 ; ++i )
{
/* get data */
data[new_index] = (i+1) ;
/* sum data to get mean */
sum += data[new_index] ;
/* if enough data has been taken to get a mean */
if ( i+1 >= frames_needed )
{
/* calculate the mean */
mean = sum / frames_needed ;
/* calculate standard deviation */
stdd = 0 ;
for ( j = 0 ; j < frames_needed ; ++j )
{
stdd += (data[j] - mean)*(data[j] - mean) ;
}
stdd = sqrt(stdd/frames_needed) ;
printf("mean = %f, standard deviation = %f\n", mean, stdd) ;
/* increment the oldest element index for the next iteration */
old_index = (old_index == frames_needed-1) ? 0 : old_index + 1 ;
/* remove old data from sum */
sum -= data[old_index] ;
}
/* increment the newest element index for next iteration */
new_index = (new_index == frames_needed-1) ? 0 : new_index + 1 ;
}
return 0 ;
}
```

Does anyone have any idea how I might be able to calculate the standard deviation without having a nested for loop, in a way perhapes similar to the example at the top.

Thanks for your time,

James

PS. I thought I would post the whole code in case anyone wanted to have a go, obviously this is trivial as the standard deviation is sqrt(2) every time.