Effacer les filtres
Effacer les filtres

How to loop function for a 2 column matrix

2 vues (au cours des 30 derniers jours)
Charlie Hillary
Charlie Hillary le 2 Déc 2020
Commenté : Charlie Hillary le 2 Déc 2020
Hi,
I have this calculation here to calculate the distance between 2 points on a globe with their latitudes and longitudes.
[arclen, az] = distance([40.333, -10.036 ], [40.333, -9.46]);
km = deg2km(arclen);
display(km)
This displays:
>> stationdist
km =
48.8236
However, I have multiple latitudes and longitudes like so:
loc1 = [40.333 -10.036;
40.333 -9.46;
40.333 -9.767;
40.333 -12.219;
41.383 -13.888;
42.581 -15.461;
43.78 -17.032;
45.05 -18.505;
46.544 -19.672;
48.039 -20.848;
49.529 -22.017;
50.278 -22.603;
53.019 -24.752;
55.506 -26.71;
57.004 -27.879;
58.207 -29.725;
58.843 -31.267;
59.102 -33.828;
59.363 -36.397;
59.623 -38.954;
59.773 -41.297;
59.902 -43.015;
59.823 -42.399;
59.799 -42.004;
59.753 -45.112;
59.434 -45.666;
59.068 -46.083;
56.916 -47.422;
55.842 -48.093;
53.692 -49.433;
53 -51.1;]
I need to perform the calculation between each row, then each distance needs to be a sum of itself and previous distances. It should look like this, assuming only 4 columns are used and that stations are calculated to be roughly 50km apart.
>> stationdist
km =
48.8236
96.3574
156.3246
201.4127
How would I create this loop with my given matrix?
Charlie

Réponse acceptée

Stephan
Stephan le 2 Déc 2020
Modifié(e) : Stephan le 2 Déc 2020
You do not need a loop - the distance function is vectorized and accepts vector-inputs. You simply need to use indexing to get what you want:
[arclen, az] = distance([loc1(1:end-1,1), loc1(1:end-1,2)], [loc1(2:end,1), loc1(2:end,2)]);
km = deg2km(arclen);
This should return a vector of km with all values.
  1 commentaire
Charlie Hillary
Charlie Hillary le 2 Déc 2020
Thanks, a lot more simple than prev. thought!
Charlie

Connectez-vous pour commenter.

Plus de réponses (1)

Ameer Hamza
Ameer Hamza le 2 Déc 2020
I don't have the mapping toolbox, so following code is untested
dist = zeros(size(loc1,1)-1,1);
for i = 1:size(loc1,1)-1
[arclen, az] = distance(loc1(i,:), loc1(i+1,:));
dist(i) = deg2km(arclen);
end
stationdist = cumsum(dist)
  1 commentaire
Charlie Hillary
Charlie Hillary le 2 Déc 2020
Hi Ameer,
This worked great too, thanks a lot. I will now find a way to sum the distances!
Charlie

Connectez-vous pour commenter.

Catégories

En savoir plus sur Sparse Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by