0

I have the coordinates (x=lon_points, y=lat_points) for a set of points. All I want to check is if these points are located outside of or inside/on a set of 0.5x0.5 grid boxes whose center coordinates are specified by (x=lon_gridbox, y=lat_gridbox).

The code that I am currently running inside the for-loop is as below. Although, I am performing this operation for a huge number of grid boxes, for the ease of representation I am only providing the code here for a limited number of grid boxes.

I want to perform this operation without using the for loop. The reason being that it is taking a lot of time for the huge number of grid boxes that I am actually operating on. Can someone suggest a way to perform this operation in a faster way by avoiding the for loop?

lat_points=[45.40927; 45.40961; 45.40995; 45.41029; 45.41063; 45.41097; 45.41131; 45.41165]; % y coordinates of the points 
lon_points=[-50.00022; -50.05021; -50.10021; -50.15020; -50.20019; -50.25019; -50.30018; -50.35018]; % x coordinate of the points
lon_gridbox=[-84; -84;-84;-83.5;-83.5;-83.5;-83.5;-83.5;-83;-83;-83;-83;-83;-83;-82.5]; % x coordinate for the center of each 0.5x0.5 grid box
lat_gridbox=[27; 27.5;28;26.5;27;27.5;28;28.5;26.5;27;27.5;28;28.5;29;26.5]; % y coordinate for the center of each 0.5x0.5 grid box
xv=[lon_gridbox(:,1)-0.25,lon_gridbox(:,1)+0.25,lon_gridbox(:,1)+0.25,lon_gridbox(:,1)-0.25,lon_gridbox(:,1)-0.25];% x coordinates of the vertices for each 0.5x0.5 grid box                                                                                                                                                                                      
yv=[lat_gridbox(:,1)-0.25,lat_gridbox(:,1)-0.25,lat_gridbox(:,1)+0.25,lat_gridbox(:,1)+0.25,lat_gridbox(:,1)-0.25];% y coordinates of the vertices for each 0.5x0.5 grid box
int=[];        
for n=1:length(lat_gridbox(:,1))
   [on in]  = inpolygon(lat_points(:,1),lon_points(:,1),xv(n,:),yv(n,:)); % checking if the points fall outside or inside/on the grid box defined by the vertices, xv and yv.
   int=[int;[lon_gridbox(n,1),lat_gridbox(n,1),in',on']];
end  
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
Srv
  • 1
  • 1
  • 1
    Your code is not slow because of the loop, but because of `inpolygon`, which is expensive. You don’t need `inpolygon` to check if a point is inside a box. You want to check if the latitude is within 0.5 and the longitude is within 0.5 of the center of the box. This is a trivial check. – Cris Luengo Sep 28 '19 at 22:11
  • Yes. That's correct. I will apply that. Thank you. – Srv Sep 28 '19 at 22:16

0 Answers0