mysql matlab for循环嵌套循环,无限,而嵌套在MATLAB中的for循环

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值