对于循环不能按预期工作

时间:2014-09-15 19:05:27

标签: matlab for-loop matrix

我正在计算GPS坐标(纬度,长度,高度)之间的距离和速度,当我使用单个值时,它似乎运行良好。但是,我有一个79个GPS坐标矩阵(3x79矩阵),我想找到每两个连续点之间的距离和速度。当我尝试使用for循环时,我得到的输出除了第一个和最后一个值(非常高)之外都是零。

我可能正在做些傻事,但我可以发现它......任何建议都值得赞赏:)

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 个答案:

答案 0 :(得分:2)

看起来您正在以无意的方式重用distance变量,以及velocity循环结束时的for变量。您正在改变distance变量,然后尝试将其重新整形为矩阵。您需要更改此变量,然后调用要将矩阵存储在其他位置的位置。此外,distancevelocity看起来像是单个数组,因此第一维的:访问权限是多余的。因此,请尝试这样做:

distance = zeros(1,77); %// NEW - Preallocate distance array
velocity = zeros(1,77); %// NEW - Preallocate velocity array
R=6378.1e3; %// NEW - Leave outside for loop.  Constant at each iteration
for k=1:77

    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));

    dist = R * c * 1000; %// convert to meters - NEW - change variable

    height = copter_llh(3,k+1) - copter_llh(3,k); 
    %// stepsize =0.1min ___speed in m/s 
    distance(k) = sqrt((dist^ 2) + (height^2)); %// NEW - Assign directly to distance array
    velocity(k) = distance/0.1*60; %// NEW - Assign directly to velocity array
end %-----

此代码现在应分别存储distancevelocity中存储的77个距离和速度。尝试一下,让我知道它是否有效!


旁注

您可以在没有任何for循环的情况下以完全矢量化的方式计算此值。您可以使用diff为您计算相邻距离。因此,您实际上可以这样做:

R=6378.1e3;
latDistance = diff(copter_llh(1,:)); % // NEW
lonDistance = diff(copter_llh(2,:)); %// NEW

a = sin(latDistance / 2) .* sin(latDistance / 2) + cos(copter_llh(1,1:end-1))...
  .*cos(copter_llh(1,2:end)) .* sin(lonDistance / 2) .* sin(lonDistance / 2);
c = 2 *atan2(sqrt(a), sqrt(1 - a));

dist = R * c * 1000; %// convert to meters - NEW - change variable

height = diff(copter_llh(3,:));
distance = sqrt((dist.^2) + (height.^2));  %// NEW
velocity = distance/0.1*60; %// NEW

上面的代码应该等同于你的for循环方法,但是请记住始终先编写对你有意义的代码,然后再开始进行任何优化。这是编码的最佳方式!