How to find distance in a for loop using d=distance

22 vues (au cours des 30 derniers jours)
Bradley
Bradley le 6 Déc 2024 à 15:20
Réponse apportée : Mathieu NOE le 6 Déc 2024 à 15:36
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!

Réponses (1)

Mathieu NOE
Mathieu NOE le 6 Déc 2024 à 15:36
hello
  • 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
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

Catégories

En savoir plus sur Geographic Plots dans Help Center et File Exchange

Tags

Produits


Version

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by