Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array data normalization

Tags:

arrays

c#

I have an array of values (between -1.0 and 1.0) that represent intensity (Black to White). I need a way to map the double values from -1.0 through 1.0 to 0 through 255 and back.

More generalized, I have an array of data and I need to map from the min and max value of the data to a supplied min and max. Basic structure should be like:

private static int[] NormalizeData(double[] data, int min, int max)
{
    var sorted = data.OrderBy(d => d);
    double dataMax = sorted.First();
    double dataMin = sorted.Last();
    int[] ret = new int[data.Length];

    for (int i = 0; i < data.Length; i++)
    {
        ret[i] = (int)data[i];  // Normalization here
    }

    return ret;
}
like image 320
joe_coolish Avatar asked Dec 17 '22 16:12

joe_coolish


1 Answers

This works:

private static int[] NormalizeData(IEnumerable<double> data, int min, int max)
{
    double dataMax = data.Max();
    double dataMin = data.Min();
    double range = dataMax - dataMin;

    return data
        .Select(d => (d - dataMin) / range)
        .Select(n => (int)((1 - n) * min + n * max))
        .ToArray();
}

The first select normalizes the input to be from 0 to 1 (0 being minimum, 1 being the maximum). The second select takes that normalized number, and maps it to the new minimum and maximum.

Note that using the LINQ Min() and Max() functions are faster than sorting the input for larger datasets: O(n) vs. O(n * lg(n)).

Also, if you want to go the other way, then you'll want it to return doubles instead of ints.

like image 175
Cameron Avatar answered Jan 01 '23 12:01

Cameron