while loop not ending, juz stopped at i = 3
1 次查看(过去 30 天)
显示 更早的评论
Hi, I am new to Matlab.
I wrote a below script to get the vector fwd = [3 8]. If I put breakpoints I could see the fwd I want. but the code never ended.
Could anyone please point out the mistake? thanks in advance!
clc; clear; close all
a = [1 2 3 4 2 3 4 5 6 3 4 5 6 8 9 10 9 8 7 6 7 8 9 8 7 5 4 3 2 4 5 3 2 1];
start = min(a)+2;
ed = max(a) -2;
m = length(a);
f = 1;
i = 2;
while i < m
if a(i) >= start && a(i-1) <= start && a(i+1) > a(i)
fwd(f,1) = a(i);
for j = i+1:m-1
if a(j+1) > ed && a(j+2) >= a(j+1) && a(j) < a(j+1)
fwd(f,2) = a(j);
end
end
else
i = i+1;
end
end
0 个评论
回答(1 个)
Bjarke Skogstad Larsen
2020-5-15
编辑:Bjarke Skogstad Larsen
2020-5-15
In your code, once the following is true, it is always true, since you don't modify any of the variables inside the 'if'
if a(i) >= start && a(i-1) <= start && a(i+1) > a(i)
Thus, your variables i and m stay the same after this point, and you get stuck in an infinite loop.
Maybe you intended i to increase after each iteration regardless of the 'if'?
In this case, the following should work, though it doesn't result in the result you say is correct: [3 8]
while i < m
if a(i) >= start && a(i-1) <= start && a(i+1) > a(i)
fwd(f,1) = a(i);
for j = i+1:m-1
if a(j+1) > ed && a(j+2) >= a(j+1) && a(j) < a(j+1)
fwd(f,2) = a(j);
end
end
end
i = i+1;
end
It's difficult to get any closer to solving this without any explanation of what your code is supposed to do.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!