Skip to content

Instantly share code, notes, and snippets.

@Akira-Hayasaka
Created May 18, 2013 02:00
Show Gist options
  • Save Akira-Hayasaka/5602956 to your computer and use it in GitHub Desktop.
Save Akira-Hayasaka/5602956 to your computer and use it in GitHub Desktop.
smooth filter
//
// BoxFIR.h
// FilteringTrial
//
// Created by Akira on 5/18/13.
//
//
#ifndef FilteringTrial_BoxFIR_h
#define FilteringTrial_BoxFIR_h
/*
Boxcar finite impulse response filter.
http://en.wikipedia.org/wiki/Boxcar_function
http://en.wikipedia.org/wiki/Window_function#Rectangular_window
*/
class BoxFIR
{
int numCoeffs; //MUST be > 0
vector<double> b; //Filter coefficients
vector<double> m; //Filter memories
public:
BoxFIR(int _numCoeffs):
numCoeffs(_numCoeffs)
{
if (numCoeffs<1)
numCoeffs = 1; //Must be > 0 or bad stuff happens
double val = 1./numCoeffs;
for (int ii=0; ii<numCoeffs; ++ii) {
b.push_back(val);
m.push_back(0.);
}
}
void filter(vector<double> &a)
{
double output;
for (int nn=0; nn<a.size(); ++nn)
{
//Apply smoothing filter to signal
output = 0;
m[0] = a[nn];
for (int ii=0; ii<numCoeffs; ++ii) {
output+=b[ii]*m[ii];
}
//Reshuffle memories
for (int ii = numCoeffs-1; ii!=0; --ii) {
m[ii] = m[ii-1];
}
a[nn] = output;
}
}
};
#endif
BoxFIR box(2); //If this is 1, then no filtering happens, use bigger ints for more smoothing
//Make a rising saw function for demo
vector<double> a;
a.push_back(0.); a.push_back(0.25); a.push_back(0.5); a.push_back(0.75); a.push_back(1.);
a.push_back(0.); a.push_back(0.25); a.push_back(0.5); a.push_back(0.75); a.push_back(1.);
a.push_back(0.); a.push_back(0.25); a.push_back(0.5); a.push_back(0.75); a.push_back(1.);
a.push_back(0.); a.push_back(0.25); a.push_back(0.5); a.push_back(0.75); a.push_back(1.);
box.filter(a);
for (int nn=0; nn<a.size(); ++nn)
{
cout << a[nn] << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment