MATLAB: How to use histc() correctly

While binning some neural spikes into bins of fixed time-width, I kept getting columns of 0’s at the end of a bin. This is clearly a coding error since there’s no way that hundreds of neurons just decide not to fire at the same time at the last bin of every time interval I’m analyzing, regardless of the bin size.

The culprit, is the behavior of histc(). According to MATHWORKS:

bincounts = histc(x,binranges) counts the number of values in x that are within each specified bin range. The input, binranges, determines the endpoints for each bin. The output, bincounts, contains the number of elements from x in each bin.

However, the following gives:

>> data=[1 1.5 2 3 4 4.5 5 6 7 7 7];
>> length(data)

ans =


>> histc(data, [1:1:5])

ans =

2 1 1 2 1

Only 7 out of the 11 elements are actually being counted by the histc. Scrolling down to histc’s input argument docs, we see the following:

For example, if binranges equals the vector [0,5,10,13], then histc creates four bins. The first bin includes values greater than or equal to 0 and strictly less than 5. The second bin includes values greater than or equal to 5 and less than 10, and so on. The last bin contains the scalar value 13.

So the last bin just has completely different behavior from the other bins, which makes no sense to me. The correct way to bin the example data into [1:1:5] is then:

>> histc(data, [1:1:5, inf])

ans =

2 1 1 2 5 0
>> ans(1:end-1)

ans =

2 1 1 2 5



About collapsedwavefn

I have a lot of thoughts. Some of them I'd like to share.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s