Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting 2D coordinates into bins in MATLAB

I am trying to sort random coordinates on a 2D cartesian grid using MATLAB into "bins" defined by a grid.

For example if I have a 2D domain with X ranging from [-1,1] and Y from [-1,1] and I generate some random coordinates within the domain, how can I "count" how many coordinates fall into each quadrant?

I realize that for and if statements can be used to determine the if each coordinate is within the quadrants, but I would like to scale this to much larger square grids that have more than just 4 quadrants.

Any concise and efficient approach would be appreciated!


1 Answers

Below is an example adapted from the code I mentioned.

The resulting binned points are be stored the variable subs; Each row contains 2d subscript indices of the bin to which a point was assigned.

% 2D points, both coordinates in the range [-1,1]
XY = rand(1000,2)*2 - 1;

% define equal-sized bins that divide the [-1,1] grid into 10x10 quadrants
mn = [-1 -1]; mx = [1 1];  % mn = min(XY); mx = max(XY);
N = 10;
edges = linspace(mn(1), mx(1), N+1);

% map points to bins
% We fix HISTC handling of last edge, so the intervals become:
% [-1, -0.8), [-0.8, -0.6), ..., [0.6, 0.8), [0.8, 1]
% (note the last interval is closed on the right side)
[~,subs] = histc(XY, edges, 1); 
subs(subs==N+1) = N;

% 2D histogram of bins count
H = accumarray(subs, 1, [N N]);

% plot histogram
imagesc(H.'); axis image xy
set(gca, 'TickDir','out')
colormap gray; colorbar
xlabel('X'); ylabel('Y')

% show bin intervals
ticks = (0:N)+0.5;
labels = strtrim(cellstr(num2str(edges(:),'%g')));
set(gca, 'XTick',ticks, 'XTickLabel',labels, ...
    'YTick',ticks, 'YTickLabel',labels)

% plot 2D points on top, correctly scaled from [-1,1] to [0,N]+0.5
XY2 = bsxfun(@rdivide, bsxfun(@minus, XY, mn), mx-mn) * N + 0.5;
line(XY2(:,1), XY2(:,2), 'LineStyle','none', 'Marker','.', 'Color','r')

2d_bins

like image 60
Amro Avatar answered Mar 22 '26 06:03

Amro