while loop not ending, juz stopped at i = 3
조회 수: 2 (최근 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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!