while loop not ending, juz stopped at i = 3

1 vue (au cours des 30 derniers jours)
HYZ
HYZ le 15 Mai 2020
Commenté : HYZ le 15 Mai 2020
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

Réponses (1)

Bjarke Skogstad Larsen
Bjarke Skogstad Larsen le 15 Mai 2020
Modifié(e) : Bjarke Skogstad Larsen le 15 Mai 2020
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 commentaire
HYZ
HYZ le 15 Mai 2020
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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by