For loop not working as desired
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi,
I am calculating the distance and velocity between GPS coordinates (lat,long,height) and it appears to work well when I used single values. However, I have a matrix of 79 GPS coordinates (3x79 matrix) and I want to find the distance and speed between each two consecutive points. When I try to use a for loop the output I get is all zeros apart from the first and last value.
I am probably doing something silly but I can spot it...any suggestions are appreciated :)
for k=1:77
R=6378.1e3;
latDistance = copter_llh(1,k+1) - copter_llh(1,k);
lonDistance = copter_llh(2,k+1) - copter_llh(2,k);
a = sin(latDistance / 2) * sin(latDistance / 2) + cos(copter_llh(1,k))...
*cos(copter_llh(1,k+1)) * sin(lonDistance / 2) * sin(lonDistance / 2);
c = 2 *atan2(sqrt(a), sqrt(1 - a));
distance = R * c * 1000; % convert to meters
height = copter_llh(3,k+1) - copter_llh(3,k);
distance = sqrt((distance^ 2) + (height^2));
velocity = distance/0.1*60; % stepsize =0.1min ___speed in m/s
distance(:,k)=(distance);
velocity(:,k)=(velocity);
end
댓글 수: 1
dpb
2014년 9월 15일
Start with the deltas can be gotten entirely out of the loop...
lat=diff(copter_llh(1,:),1,2);
lon=diff(copter_llh(2,:),1,2);
ht=diff(copter_llh(3,:),1,2);
The above does all 78 differences for a 79-column array; your loop only will return 77 differences from 2-1 thru 78-77; I'm not understanding the why of that; perhaps there's something irregular in the last column or it wraps around or something???
After that, the products can be computed with .* "dot" operator if you fix the lengths to be consistent and the distance computed from the dot multiply of the vectors as well.
Should be able to eliminate the loop entirely.
채택된 답변
Star Strider
2014년 9월 15일
I can’t run your code, but one item that would seem to be a problem is:
distance = sqrt((distance^ 2) + (height^2));
velocity = distance/0.1*60; % stepsize =0.1min ___speed in m/s
distance(:,k)=(distance);
velocity(:,k)=(velocity);
You’re assigning ‘distance’ and ‘velocity’ scalars and then as arrays. Won’t work. This example illustrates the same problem:
for k1 = 1:10
xt = k1^2;
xt(k1) = xt;
end
Renaming the scalar solves the problem:
for k1 = 1:10
xt2 = k1^2;
xt(k1) = xt2;
end
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!