# Replace values in 2D arrays with bin numbers (down sample)

I have a 2D array with a lot of large values in it. This is the histogram for the data with the values grouped into 16 different bins:

I want to replace all the values in the array with their bin number so that each value in the array is just one of 16 possible values (0-15). How can I do that?

• What does "2D" have to do with anything here? What does "down sample" have to do with anything here? – David G. Stork Dec 6 '17 at 1:15
• @DavidG.Stork The values in this case are frequencies. When frequencies are binned in this way it is sometimes referred to as "downsampling". Since my data is in a 2D array, ie list of lists, (notice the Flatten function above), I need a solution that operates on a list of lists. – Tyler Durden Dec 6 '17 at 1:23
• Have you tried ArrayResample? – aardvark2012 Dec 6 '17 at 3:17

## 1 Answer

There's a nice image processing function you can exploit to quantize your data. Say the array is called data (for demonstration, make it up from random numbers). Then quan quantizes this to only n=3 values (you can do any number, like 16). The Tally shows that you have indeed only n values in the quantized array.

data = RandomReal[{0, 1}, {100, 100}];
quan = ImageData[ColorQuantize[Image[data], 3]];
tal = Tally[Flatten[ImageData[ColorQuantize[Image[data], 3]]]];
quan /. Thread[Sort[tal[[All, 1]]] -> Range[Length[tal]]]


The final line sorts the values, and replaces the numbers with integers, as requested in the comment.

• Ok, that is an idea. The main issue I see is that I need the values to be equally separated, like 1, 2, 3, 4 ... where the values in 1 are less than the values in 2, etc. The ColorQuantize function seems to generate random numbers, like "0.125955". – Tyler Durden Dec 6 '17 at 3:02
• Then why not assign each of the "random" numbers to an integer? I've updated the answer. – bill s Dec 6 '17 at 4:06