array indexing and binning

Hello there dear community, I need some help with matlab. I have an array of lets say 3000 elements with an array range of 2.88:4.88. I would like to create 10 bins, as bin#1 will contain all array elements within the range: 2.88 : (2.88+10%); bin#2 will contain all array elements within the range: (2.88+10%) : (2.88+20%) and so on. In other words, I want to group my array elements into 10 groups, as group one will contain all array values within 0:10% of the array range, the second group will contain all array values within 10%-20% of the array range and so on. I am thinking of using a loop and saving all 10 bins into a structure, but having trouble writing the code.
Any help is deeply appreciated! Thank you!

5 Comments

A = linspace(2.88,4.88,3000);
B = mat2cell(reshape(A,numel(A)*.1,[]),numel(A)/10,ones(10,1));
Andrei, the question is not about an array with equally spaced values: the question is about an array that contains values in a known range. It is a histogram binning problem, not a reshaping problem.
Andrei, the question is not about an array with equally spaced values: the question is about an array that contains values in a known range. It is a histogram binning problem, not a reshaping problem.
@Walter: why didn't you post the histc solution as an answer?
There was a MATLAB Answers bug that prevented Answers from being posted to this question. I notified Mathworks last night and they fixed it since then.

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 10 Sep 2011

0 votes

bins = linspace(min(x), max(x), 11) bins(end) = inf; [bincounts, binidx] = histc(x, bins);
Then for any particular index x(K), it fell in to bin binidx(K).
Note: your specification is ambiguous about what should happen at exactly 2.88+10% . Your first criteria requires it to be in the first bin, but your second criteria requires that it be in the second bin. The routine I used, histc, would place it in the first bin, as it uses bins(K) <= x < bins(K+1) and then special cases the last bin to hold the values that are exactly bins(end) . The extra line of setting bins(end) to infinity ensures that the second-last bin holds all the remaining finite values. As I constructed it using 11 bins with the linspace() step, the result of that will be 10 bins of useful numbers and the 11th bin will be empty (unless the data contains infinity.)

Asked:

on 9 Sep 2011

Community Treasure Hunt

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

Start Hunting!