MATLAB: Histc and bin-width determination

histc

Hi
Given I have the following data:
A = [100 150 190 200 250 300 350 370 390 400 400]
And I want 3 bins: From 100 to 200, 200 to 300, and 300 to 400.
How do I do that with histc?
What I tried so far was:
edges = linspace(min(stim_durations),max(stim_durations),4);
counts = histc(stim_durations, edges);
But that results in 4 bins with "400" having its own bin..how can I solve that?

Best Answer

The simplest solution on a recent enough version of matlab (2014b or newer) is to use histcounts which behaves exactly as you want:
>>A = [100 150 190 200 250 300 350 370 390 400 400];
>>hiscounts(A, [100 200 300 400])
ans =
3 2 6
As per histc documentation, the last edge is its own bin and you can't do anything about that. If you want 400 to be included in the third bin and still use histc, you have to shift the edge of the 4th value slightly above 400 (and discard that last bin):
A = [100 150 190 200 250 300 350 370 390 400 400];
edges = linspace(min(A),max(A),4);
edges(end) = edges(end) + eps(edges(end)); %or any value greater than eps(400);
counts = histc(A, edges);
counts = counts(1:end-1)