Skip to content

Instantly share code, notes, and snippets.

@vikeri

vikeri/clean_mean.c

Created Mar 30, 2017
Embed
What would you like to do?
Cleaned mean in C
#include <stdio.h>
#include <math.h>
#include <stdint.h>
#define nsamples 254
float calculate_mean(uint16_t data[]) {
float sum = 0.0, mean;
uint16_t good_samples = 0;
uint16_t i;
for(i=0; i<nsamples; ++i)
{
if (data[i]!=0) {
++good_samples;
}
sum += data[i];
}
return sum/good_samples;
}
float calculate_sd(uint16_t *data, float mean)
{
float standard_deviation = 0.0;
uint16_t i;
for(i=0; i<nsamples; ++i) {
standard_deviation += pow(data[i] - mean, 2);
}
return sqrt(standard_deviation/nsamples);
}
uint16_t calc_filtered_mean(uint16_t *data) {
float mean = calculate_mean(data);
float sd = calculate_sd(data, mean);
uint16_t upper_cutoff = (uint16_t) round(mean + 2 * sd);
uint16_t lower_cutoff = (uint16_t) round(mean - 2 * sd);
uint16_t i;
for (i = 0; i<nsamples; ++i){
data[i] = (data[i]<lower_cutoff || data[i]>upper_cutoff) ? 0 : data[i];
}
return round(calculate_mean(data));
}
int main()
{
uint16_t data[nsamples] = {12120,12118,12128,12141,12143,12149,12148,12147,12148,12145,12142,12137,12139,12137,12132,12126,12120,12123,12119,12187,12182,12192,12176,12195,12213,12193,12183,12188,12190,12189,12188,12183,12185,12188,12190,12188,12185,12186,12187,12192,12190,12184,12188,12189,12191,12185,12190,12185,12189,12187,12191,12189,12190,12187,12186,12187,12184,12183,12188,12185,12186,12185,12190,12189,12187,12186,12186,12192,12189,12191,12187,12193,12184,12186,12186,12186,12188,12189,12187,12187,12191,12188,12189,12182,12190,12189,12188,12187,12186,12187,12189,12192,12184,12189,12187,12192,12187,12190,12189,12186,12186,12187,12189,12191,12184,12191,12190,12189,12191,12188,12185,12186,12190,12186,12187,12189,12185,12185,12186,12190,12188,12187,12191,12186,12192,12189,12192,12186,12190,12189,12188,12194,12188,12186,12186,12190,12188,12188,12187,12187,12188,12186,12187,12186,12186,12188,12190,12186,12185,12184,12184,12187,12189,12189,12190,12186,12186,12183,12190,12185,12190,12188,12183,12191,12191,12191,12185,12189,12190,12186,12188,12189,12185,12187,12185,12188,12192,12186,12189,12185,12181,12188,12190,12182,12183,12191,12186,12186,12190,12190,12187,12188,12189,12185,12190,12185,12184,12188,12184,12192,12190,12189,12187,12188,12190,12186,12189,12192,12190,12190,12190,12189,12186,12187,12184,12189,12187,12188,12193,12184,12187,12187,12192,12185,12187,12193,12190,12188,12190,12188,12193,12189,12185,12189,12183,12187,12188,12188,12188,12188,12184,12184,12188,12193,12191,12185,12193,12186,12186,12191,12187,12190,12187,12189};
printf("Mean : %.i\n",calc_filtered_mean(data));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment