# Split matrix into square cells

3 vues (au cours des 30 derniers jours)
A le 23 Avr 2022
Commenté : A le 27 Avr 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 commentairesAfficher AucuneMasquer Aucune
Matt J le 23 Avr 2022
What does "0.5m" signify? I suggest showing the desired output for your example.
A le 24 Avr 2022
0.5 is the dimenstions of the cell

Connectez-vous pour commenter.

### Réponse acceptée

Voss le 23 Avr 2022
Modifié(e) : Voss le 24 Avr 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 commentairesAfficher 7 commentaires plus anciensMasquer 7 commentaires plus anciens
Voss le 27 Avr 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 le 27 Avr 2022
Okay that makes more sense, thank you!

Connectez-vous pour commenter.

### Plus de réponses (1)

Steven Lord le 24 Avr 2022
Use the histcounts2 function.
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by