필터 지우기
필터 지우기

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 CenterFile Exchange에서 Sparse Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by