在MATLAB中将2D坐标排序为bin

时间:2014-06-27 03:14:20

标签: matlab grid 2d binning

我正在尝试使用MATLAB将2D笛卡尔网格上的随机坐标排序到" bins"由网格定义。

例如,如果我有一个2D域,其中X范围为[-1,1],Y来自[-1,1],并且我在域内生成一些随机坐标,我怎样才能计算"计算&#34 ;每个象限有多少个坐标?

我意识到for和if语句可用于确定每个坐标是否在象限内,但我想将其缩放到更大的方形网格,这些网格只有4个象限。

任何简洁有效的方法都会受到赞赏!

1 个答案:

答案 0 :(得分:6)

以下是改编自the code I mentioned的示例。

生成的分箱点存储在变量subs中;每行包含分配点的bin的2d下标索引。

% 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