MATLAB: For loop not working as desired

for loopmatrix

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 (3×79 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

Best Answer

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