How to loop function for a 2 column matrix

2 ビュー (過去 30 日間)
Charlie Hillary
Charlie Hillary 2020 年 12 月 2 日
コメント済み: Charlie Hillary 2020 年 12 月 2 日
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

採用された回答

Stephan
Stephan 2020 年 12 月 2 日
編集済み: Stephan 2020 年 12 月 2 日
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 件のコメント
Charlie Hillary
Charlie Hillary 2020 年 12 月 2 日
Thanks, a lot more simple than prev. thought!
Charlie

サインインしてコメントする。

その他の回答 (1 件)

Ameer Hamza
Ameer Hamza 2020 年 12 月 2 日
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 件のコメント
Charlie Hillary
Charlie Hillary 2020 年 12 月 2 日
Hi Ameer,
This worked great too, thanks a lot. I will now find a way to sum the distances!
Charlie

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeSparse Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by