views:

51

answers:

1

Hi, I have a probably pretty simple question but I am still not sure!

Actually I only want to smooth a histogram, and I am not sure which of the following to methods is correct. Would I do it like this:

vector<double> mask(3);
mask[0] = 0.25; mask[1] = 0.5; mask[2] = 0.25;

vector<double> tmpVect(histogram->size());
for (unsigned int i = 0; i < histogram->size(); i++)
  tmpVect[i] = (*histogram)[i];

for (int bin = 1; bin < histogram->size()-1; bin++) {
  double smoothedValue = 0;
  for (int i = 0; i < mask.size(); i++) {
    smoothedValue += tmpVect[bin-1+i]*mask[i];
  }
  (*histogram)[bin] = smoothedValue;
}

Or would you usually do it like this?:

vector<double> mask(3);
mask[0] = 0.25; mask[1] = 0.5; mask[2] = 0.25;

for (int bin = 1; bin < histogram->size()-1; bin++) {
  double smoothedValue = 0;
  for (int i = 0; i < mask.size(); i++) {
    smoothedValue += (*histogram)[bin-1+i]*mask[i];
  }
  (*histogram)[bin] = smoothedValue;
}

My Questin is: Is it resonable to copy the histogram in a extra vector first so that when I smooth at bin i I can use the original i-1 value or would I simply do smoothedValue += (*histogram)[bin-1+i]*mask[i];, so that I use the already smoothed i-1 value instead the original one.

Regards & Thanks for a reply.

+1  A: 

Your intuition is right: you need a temporary vector. Otherwise, you will end up using partly old values, and partly new values, and the result will not be correct. Try it yourself on paper with a simple example.

There are two ways you can write this algorithm:

  1. Copy the data to a temporary vector first; then read from that one, and write to histogram. This is what you did in your first code fragment.
  2. Read from histogram and write to a temporary vector; then copy from the temporary vector back to histogram.

To prevent needless copying of data, you can use vector::swap. This is an extremely fast operation that swaps the contents of two vectors. Using strategy 2 above, this would result in:

vector<double> mask(3);
mask[0] = 0.25; mask[1] = 0.5; mask[2] = 0.25;

vector<double> newHistogram(histogram->size());

for (int bin = 1; bin < histogram->size()-1; bin++) {
  double smoothedValue = 0;
  for (int i = 0; i < mask.size(); i++) {
    smoothedValue += (*histogram)[bin-1+i]*mask[i];
  }
  newHistogram[bin] = smoothedValue;
}

histogram->swap(newHistogram);
Thomas