필터 지우기
필터 지우기

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일
편집: 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