while loop not ending, juz stopped at i = 3

1 次查看(过去 30 天)
HYZ
HYZ 2020-5-15
评论: HYZ 2020-5-15
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

回答(1 个)

Bjarke Skogstad Larsen
编辑: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.
  1 个评论
HYZ
HYZ 2020-5-15
Thank you. I revised my code based on your advice. now it's solved.
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; r = 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
i=j+1;
else
i = i+1;
end
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by