MATLAB Answers

How to calculate the points of a line which lies inside polygons?

2 views (last 30 days)
pietro on 3 Apr 2019
Commented: pietro on 4 Apr 2019
Hi all,
I have GPS coordinates of an off-road vehicle and I have to check when the vehicle lies on a road or on a field. I have downloaded the shape file of my region, where there are the bounding box of each field. Below, you will find my code, that is very slow because in the shape file there are around 3e5 polygons. How could I speed up the code? In my opinion, the calculation could be speeded up, if I can avoud the inner for, but I do not know how can I do it.
for i=1:length(GPSData)
for iS=1:length(FieldUseSHP)
if any(a)==1
Thank you in advance
Best regards,


Show 1 older comment
pietro on 3 Apr 2019
Hi Adam,
yes, I have the coordinates of the road and of the field profiles. The problem is solved as you suggested, but the problem remains with the field. Here a picture of how my problem looks like:
as you can see the tractor line is enclosed by a field profile. In that case, I have used the approach shown above, which is very slow.
Adam Danz
Adam Danz on 3 Apr 2019
I see. What does the data look like that produces the image you shared? In other words, the brown field contains ~20 line segments and the yellow field contains 4 segments. Do you have the 20 (x,y) coordinates that produce the brown field and the 4 (x,y) coordinates that produce the yellow field?
If yes, are those coordinates used to define the polygon used in inpolygon()?
Also, what are your two loops? You should have a set of (x,y) coordinates that define the tractor's trajectory and those whould be the first inuts to the inpolygon() function.
pietro on 4 Apr 2019
I have several GPS vehicle data, each is an acquisition and the first for loops through all the acquisitions. The other for loops through all the polygons of field plot contours.
In the plot I have shown only two field countours, that are the closest to the chosen acquisition.

Sign in to comment.

Answers (1)

Matt J
Matt J on 3 Apr 2019
fconv=@(z) z(:).';
Longitude=cell2mat( cellfun( fconv, {GPSData.Longitude},'uni',0) )*pi/180;
Latitude=cell2mat( cellfun( fconv, {GPSData.Latitude},'uni',0) )*pi/180;
for iS=1:length(FieldUseSHP)
a=inpolygon(Longitude, Latitude,FieldUseSHP(iS).Lon,FieldUseSHP(iS).Lat);


Sign in to comment.