Indexing Vector of Variables

I have a column vector of numbers (we'll call it A for example). Is there a slick way to go through A and create another column vector (B) of indices? In other words, if a number in A falls in the range of 0-0.1, it will be binned (i.e., indexed) as 1 in B. If a number in A falls in the range of 0.1-0.2, it will be indexed as 2 in B. If a number in A falls in the range of 0.2-0.3, it will be indexed as 3 in B. And so on. Vector B will then serve as my Indexing vector to allocate each number of A to a certain "bin." I'm sure I could write a FOR and/or IF statement to accomplish this. But for the sake of efficiency, I wanted to ask if there was a more efficient and easier way.
Thanks,
M Ridzon

 Accepted Answer

Stephen23
Stephen23 on 15 Nov 2017
Edited: Stephen23 on 15 Nov 2017
That is what the histogram functions do very easily and efficiently:
or
or
etc.
Here is an example:
>> V = rand(1,10)
V =
0.8093 0.0174 0.3329 0.4669 0.5331 0.1471 0.9760 0.3909 0.4499 0.3305
>> B = 0:0.1:1; % bin edges
>> [~,idx] = histc(V,B)
idx =
9 1 4 5 6 2 10 4 5 4

4 Comments

The first output of histcounts is the count of how many elements fall into each bin. The third output is the array indicating which bin each element falls.
The first output of discretize is the array indicating into which bin each element falls. So I'd recommend using this function instead of histc or histcounts.
Great! I figured there was an easier way. After digging, it looks like "discretize" will also do this. In any case, what happens if a number falls smack dab on an edge? What bin does it go to?
@Matthew: did you read the discretize help? It clearly explains how the data are allocated to the bins.
Beautiful! I got my answers. Thanks a million folks!

Sign in to comment.

More Answers (0)

Asked:

on 15 Nov 2017

Commented:

on 15 Nov 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!