- the loop must stop one index value before the end
- also I would suggest you index the d value so you get (numel(TrackLat) - 1) arc lengths
- use sum to compute the total distance
How to find distance in a for loop using d=distance
3 views (last 30 days)
Show older comments
I have lat and long points and I want to see the total distance between all of the points. What im trying to figure out is how to continue this in a for loop, here is my code:
for i = 1:numel(TrackLat)
d = distance(TrackLat(1,:), TrackLong(1,:), TrackLat(2,:), TrackLong(2,:), wgs84);
end
So right now im adding the first point to the second point and I get the correct distance, now I want to add the second point to the third point and so on. Im working with a small subset of a dataset with approx. 100000 points, at the end I want to concat all of this together to get total distance traveled. I thought maybe this would work:
for i = 1:numel(TrackLat)
d = distance(TrackLat(i,:), TrackLong(i,:), TrackLat(i+1,:), TrackLong(i+1,:), wgs84);
end
but I get this error:
Index in position 1 exceeds array bounds. Index must not exceed 32.
Error in untitled7 (line 69)
d = distance(TrackLat(i,:), TrackLong(i,:), TrackLat(i+1,:), TrackLong(i+1,:), wgs84);
^^^^^^^^^^^^^^
I assume thats because when I get to the end of the loop its trying to add the last point to a point that doesnt exist. How can I go about this to calculate the total distance between a bunch of lat and long points? Thanks!
0 Comments
Answers (1)
Mathieu NOE
on 6 Dec 2024
hello
code should be like :
for i = 1:numel(TrackLat)-1
d(i) = distance(TrackLat(i,:), TrackLong(i,:), TrackLat(i+1,:), TrackLong(i+1,:), wgs84);
end
d_total = sum(d); % total distance
0 Comments
See Also
Categories
Find more on Geographic Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!