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:

enter image description here

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?

  • 1
    $\begingroup$ What does "2D" have to do with anything here? What does "down sample" have to do with anything here? $\endgroup$ – David G. Stork Dec 6 '17 at 1:15
  • $\begingroup$ @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. $\endgroup$ – Tyler Durden Dec 6 '17 at 1:23
  • $\begingroup$ Have you tried ArrayResample? $\endgroup$ – aardvark2012 Dec 6 '17 at 3:17

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.

  • $\begingroup$ 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". $\endgroup$ – Tyler Durden Dec 6 '17 at 3:02
  • $\begingroup$ Then why not assign each of the "random" numbers to an integer? I've updated the answer. $\endgroup$ – bill s Dec 6 '17 at 4:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.