John S
John S

Reputation: 235

C# method to scale values?

I have a value range from 0 to 255.

There is a method that returns an array with a min and max values within this range, i.e: 13, 15, 20, 27, 50 ... 240 where 13 is the min and 240 is the max

I need to scale these values so that 13 becomes 0 and 240 becomes 255 and scale all the other values between them proportionally.

Is there any C# method that does that?

thanks!

Upvotes: 20

Views: 17946

Answers (3)

digEmAll
digEmAll

Reputation: 57210

To scale value in a range (minScale, maxScale)

private double Scale(int value , int min, int max, int minScale, int maxScale)
{
  double scaled = minScale + (double)(value - min)/(max-min) * (maxScale - minScale);
  return scaled;
}

To find min and max from incoming array

var min = Array.Min();
var max = Array.Max();

Upvotes: 12

Graviton
Graviton

Reputation: 83254

Use this formula

y=mx+c

where m = (255-0)/(244-13) and c= -13*m

So you have to just transform the array as such

 public double[] GetScaling(double[] arr, double min, double max)
{
    double m = (max-min)/(arr.Max()-arr.Min());
    double c = min-arr.Min()*m;
    var newarr=new double[arr.Length];
    for(int i=0; i< newarr.Length; i++)
       newarr[i]=m*arr[i]+c;
    return newarr;
}

Upvotes: 23

Adam Robinson
Adam Robinson

Reputation: 185643

If you're using .NET 3.5, then LINQ can easily obtain the minimum and maximum values from any IEnumerable<T> object, which an array is.

int[] values = new int[] { 0, 1, 2, ... 255 };

int minValue = values.Min();
int maxValue = values.Max();

If you're looking for something to scale the whole array...

public static int[] Scale(int[] values, int scaledMin, int scaledMax)
{
    int minValue = values.Min();
    int maxValue = values.Max();

    float scale = (float)(scaledMax - scaledMin) / (float)(maxValue - minValue);
    float offset = minValue * scale - scaledMin;

    int[] output = new int[values.Length];

    for (int i = 0; i < values.Length; i++)
    {
        output[i] = (int)Math.Round(values[i] * scale - offset, 0);
    }

    return output;
}

Upvotes: 5

Related Questions