MATLAB Answers

0

Given the location (coordinates) of a point in a gridmesh, how can I extract the number of the grid that the point is located in?

Asked by Arian Abedin on 19 Jan 2018
Latest activity Commented on by Kelly Kearney
on 19 Jan 2018
I have an issue where I want to assign points to a specific grid number in a 2D gridmesh. For example, let's say I have a square divided into 4 grids: 1,2,3 and 4.
Now, if I know the coordinates of a point (x,y), I want to find out in which of these 4 grids (or quadrants) the point is located at, and extract the number of that grid.
For example, lets say I have a square with side lengths 1, divided into 4 equally large grids numbered 1,2,3 and 4 from left to right (the way you would read a book).
Each grid will then have sides of length 0.5. Then, a point with coordinates (0.75,0.75) would clearly exist in grid nr 2 assuming we use a standard x-y coordinate system with Origin at the bottom left corner of the square. How can I extract this grid number (4) in matlab?
Thanks in advance!
Best regards, Arian

  0 Comments

Sign in to comment.

1 Answer

Answer by Kelly Kearney
on 19 Jan 2018
 Accepted Answer

You can use the discretize function to bin points:
nx = 2;
ny = 2;
xedge = linspace(0,1,nx+1);
yedge = linspace(0,1,ny+1);
xpt = 0.75;
ypt = 0.75;
xbin = discretize(xpt, xedge); % which column?
ybin = discretize(ypt, yedge); % which row?
idx = sub2ind([ny, nx], ybin, xbin); % traslate row/column to index

  3 Comments

Thanks for your response! It seemed to work with the example I first gave. However, when I try something else (9 grids in a square with side lengths 2.4 for example) I dont seem to get the correct result.
nx = 3;
ny = 3;
xedge = linspace(0,2.4,nx+1);
yedge = linspace(0,2.4,ny+1);
xpt = 1.8;
ypt = 1.65;
xbin = discretize(xpt, xedge) % which column?
ybin = discretize(ypt, yedge) % which row?
idx = sub2ind([ny, nx], ybin, xbin) % traslate row/column to index
This should give me the answer "3", since the point (1.8,1.65) is located inside grid nr 3 if we take the viewpoint of numbering the grids from left to right (like reading a text).
I realise now I did not explain very well! The grids are numbered from top to bottom and from left to right (like reading a text). I apologize for not explaining thoroughly, seems like the code does work. Thanks alot :)
You can adjust the above example by flipping the y-coordinates for the y-bin calculation (so row 1 corresponds to the highest y value) and flip-flopping the x and y coordinates in the sub2ind call (so the matrix is traversed row-wise instead of column-wise:
nx = 3;
ny = 3;
side = 2.4;
xedge = linspace(0,side,nx+1);
yedge = linspace(0,side,ny+1);
xpt = 1.8;
ypt = 1.65;
xbin = discretize(xpt, xedge); % which column?
ybin = discretize(-ypt, -yedge(end:-1:1)); % which row?
idx = sub2ind([nx, ny], xbin, ybin) % translate row/column to index

Sign in to comment.