Split matrix into square cells

2 次查看(过去 30 天)
A
A 2022-4-23
评论: A 2022-4-27
I have a matirx 2-d matix where 1st colum is x and 2nd colum is y
[1 2
3 12
56 7;
4 5
6 5
6 8;
7 8
93 43
65 3;
7 8
93 43;]
I would like to spilt the data into square cells of 0.5m and know how many and what points are inside the cell
  2 个评论
Matt J
Matt J 2022-4-23
What does "0.5m" signify? I suggest showing the desired output for your example.
A
A 2022-4-24
0.5 is the dimenstions of the cell

请先登录,再进行评论。

采纳的回答

Voss
Voss 2022-4-23
编辑:Voss 2022-4-24
% (x,y) in units of m, presumably
xy = [1 2
3 12
56 7;
4 5
6 5
6 8;
7 8
93 43
65 3;
7 8
93 43;];
% define the grid starting at (min x, min y)-0.25, with spacing of 0.5:
x_grid = min(xy(:,1))-0.25:0.5:max(xy(:,1))+0.25;
y_grid = min(xy(:,2))-0.25:0.5:max(xy(:,2))+0.25;
% loop over grid cells:
for ii = 1:numel(x_grid)-1
for jj = 1:numel(y_grid)-1
% find points inside each cell:
idx = xy(:,1) >= x_grid(ii) & xy(:,1) < x_grid(ii+1) ...
& xy(:,2) >= y_grid(jj) & xy(:,2) < y_grid(jj+1);
if ~any(idx)
continue
end
% if some are found, print the info to the command line:
fprintf(1,'grid cell: x=%.2f->%.2f, y=%.2f->%.2f:',x_grid(ii+[0 1]),y_grid(jj+[0 1]));
fprintf(1,'%d point(s) inside: ',nnz(idx));
fprintf(1,'(%d,%d) ',xy(idx,:).');
end
end
grid cell: x=0.75->1.25, y=1.75->2.25:
1 point(s) inside:
(1,2)
grid cell: x=2.75->3.25, y=11.75->12.25:
1 point(s) inside:
(3,12)
grid cell: x=3.75->4.25, y=4.75->5.25:
1 point(s) inside:
(4,5)
grid cell: x=5.75->6.25, y=4.75->5.25:
1 point(s) inside:
(6,5)
grid cell: x=5.75->6.25, y=7.75->8.25:
1 point(s) inside:
(6,8)
grid cell: x=6.75->7.25, y=7.75->8.25:
2 point(s) inside:
(7,8) (7,8)
grid cell: x=55.75->56.25, y=6.75->7.25:
1 point(s) inside:
(56,7)
grid cell: x=64.75->65.25, y=2.75->3.25:
1 point(s) inside:
(65,3)
grid cell: x=92.75->93.25, y=42.75->43.25:
2 point(s) inside:
(93,43) (93,43)
  9 个评论
Voss
Voss 2022-4-27
That's to get the first grid cell centered on the min x and min y (and I added 0.25 on the end so the grid completely spans the points). Without that, the count missed a couple of points due to them being right on the last edge of the grid, if I recall correctly.
A
A 2022-4-27
Okay that makes more sense, thank you!

请先登录,再进行评论。

更多回答(1 个)

Steven Lord
Steven Lord 2022-4-24
Use the histcounts2 function.

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by