3

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

例如,如果我有一个 X 范围为 [-1,1] 和 Y 范围为 [-1,1] 的二维域,并且我在域内生成一些随机坐标,我如何“计算”每个象限中有多少坐标?

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

任何简洁有效的方法将不胜感激!

4

1 回答 1

6

下面是一个改编自我提到的代码的示例。

生成的分箱点存储在变量中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

于 2014-06-27T04:00:31.817 回答