MATLAB: Histogram with overlapping bins

histogramvectorization

Is there a fast way to code this ?
Say, X= [101 202 303 505] is the set of values to be binned,
and Y=
[0 100 200 300 400; 200 300 400 500 600] has information about the bin-edges, with the first row containing lower-bin edges and the second row containing upper bin-edges (so that successive bins are 0-200, 100-300, 200-400, 300-500, and 400-600)
and the result is [1,2,2,1,2].
Normally I would code this as:
out=NaN(1,size(Y,1)); for i=1:length(out) out(i) = length(find( X<=Y(2,i)&X>Y(1,i) ); end
Is there a faster/more succinct way, using a vectorized function ?
Thanks, Suresh

Best Answer

At first I'd use SUM:
out = NaN(1,size(Y,2)); % Edited: 1->2
for i=1:length(out)
out(i) = sum(X<=Y(2,i) & X>Y(1,i));
end
But for large array HISTC is much faster:
X = rand(1, 10000)*1000;
Y = 0:100:1000;
N = histc(X, Y);
N_200blocks = N + [N(2:end), 0];
EDITED: (Walter discovered my misunderstanding about the last bin) Read the help text of HISTC for the last element of N_200blocks. I assume you can omit it in the output.