I want to make a while
loop, nested in a for
loop in Matlab in order to find the distance between different pairs in the data. My data have the following form
ID lon lat time
1 33.56 40.89 803
2 32.45 41.03 803
3 35.78 39.85 803
2 33.04 40.21 804
3 36.89 40.23 804
2 33.98 39.33 806
2 33.67 39.73 809
3 37.02 40.77 809
lon
and lat
are geographical coordinates. In the for
loop, I want to take the first row from the matrix and then in the while
loop check all other rows and compute the distance between the pairs as long as the condition in the while
is true
. What I mean is that for the first row I want the program to compute the distance between the pairs 1-2, 1-3 at time 803, then the distance 1-2, 1-3 at time 803 again. When I increment the step in the for
loop by 1, again, the program should compute the distance between the pairs 2-3 at 803, then 2-3 at 804 and so on, so forth. To do that, I've written the for
loop as below:
for ii = 1:length(MM(:,4))
t = MM(ii,4);
ind1 = ii;
length(ind1);
lat1 = lat(ind1);
lon1 = lon(ind1);
jj = ii +1;
while (t <= (MM(ii,4)+5))
for jj = 2:length(MM(:,4))
ind2 = jj;
length(ind2);
lat2 = lat(ind2);
lon2 = lon(ind2);
w = MM(jj,4);
end
dis = distance(lat1, lon1, lat2, lon2);
t = t + 1;
end
if dis <= 1
[contact] = [ind1, ind2, t, w];
end
end
With this for
loop I get an infinite while
loop. My question is why do I get this infinite while
loop and how am I supposed to make it work as I described?
I finally found the answer. I post it here for future use.
for ii = 1:length(MM(:,4))
t = MM(ii,4);
ind1 = ii;
length(ind1);
lat1 = lat(ind1);
lon1 = lon(ind1);
jj = ii + 1;
while (MM(jj,4) - t <= 5)
ind2 = jj;
length(ind2);
lat2 = lat(ind2);
lon2 = lon(ind2);
dis = distance(lat1, lon1, lat2, lon2);
if dis <= 1
contact = [MM(ind1,1), MM(ind2,1), t, MM(jj,4)]
else
fprintf('There is no distance smaller than 1km\n')
end
jj = jj + 1;
end
end
As it seems the nested for
loop in the while
was wrong and without any use at all. The second problem was the condition in the while
. The comparison, I previously made in the while
condition was written backwards and had no meaning. And the third problem was the if
statement. By putting the if
statement in the while
loop, I had the result in the contact.
来源:https://stackoverflow.com/questions/33108192/infinite-while-nested-in-a-for-loop-in-matlab