Split matrix into square cells

1 visualización (últimos 30 días)
A
A el 23 de Abr. de 2022
Comentada: A el 27 de Abr. de 2022
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 comentarios
Matt J
Matt J el 23 de Abr. de 2022
What does "0.5m" signify? I suggest showing the desired output for your example.
A
A el 24 de Abr. de 2022
0.5 is the dimenstions of the cell

Iniciar sesión para comentar.

Respuesta aceptada

Voss
Voss el 23 de Abr. de 2022
Editada: Voss el 24 de Abr. de 2022
% (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 comentarios
Voss
Voss el 27 de Abr. de 2022
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 el 27 de Abr. de 2022
Okay that makes more sense, thank you!

Iniciar sesión para comentar.

Más respuestas (1)

Steven Lord
Steven Lord el 24 de Abr. de 2022
Use the histcounts2 function.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by