Search code examples
matlabsorting

Maximizing count by location


I have a dataset of particles in space, each in the range (x,y) in [0,1]^2. I have discretized meshes x and y, and am looking for an efficient way of finding the meshpoint containing the maximum particles. My first attempt:

max_count = -inf;
for i = 1:length(x)-1
    for j = 1:length(y)-1
        cnt = size(find(particles(:,1) >= x(i) & particles(:,1) <= x(i+1) & particles(:,2) >= y(j) & particles(:,2) <= y(j+1)),1);
        max_count = max(max_count,cnt);
    end
end

Of course, this was pretty slow. Much faster was to send the data to a histogram2 call and extract the data from that

bins = histogram2(particles(:,1),particles(:,2),x,y);
max_count = max(max(bins.Values));

This is definitely faster, but still takes up a decent amount of time, given that I'm running this every iteration of a loop that goes on for thousands of steps. Is there a faster way? I've looked at the discretize function, but that only works for 1d arrays. Any sort of 2d analog to this function would be great.


Solution

  • You should use histcounts2 to compute a bivariate histogram. It has more or less the same syntax as histogram2, but it doesn’t generate any graphics.