Break command doesn't stop the For loop
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Ketan Patel
le 24 Juin 2020
Commenté : Ketan Patel
le 24 Juin 2020
Hi all,
Can anybody please explain me why the 'break' command doesn't work in the following code?
Thank you!
H = 1:4;
h = H';
for i = h
G = 3-i;
if G < 0
break;
end
end
0 commentaires
Réponse acceptée
Stephen23
le 24 Juin 2020
Modifié(e) : Stephen23
le 24 Juin 2020
"Can anybody please explain me why the 'break' command doesn't work in the following code?"
Explanation: The reason is because of the orientation of h.
You define H with size 1x4 (i.e. a row vector) and from that you ctranspose it so that h has size 4x1.
The for documentation explains that for iterates over the columns of the values array (not over the elements as you probably expected), so you defined a loop which iterates just once and for which i will be that column vector. You can confirm the size of i simply by printing it after the loop.
So i also has size 4x1, and therefore G also has size 4x1:
>> G
G =
2
1
0
-1
The if documentation states that its condition "... expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false."
Your condition G<0 is certainly non-empty, but are all of its elements non-zero? Lets have a look:
>> G < 0
ans =
0
0
0
1
No, first three elements are false/zero. Therefore your condition expression is false, and so the code inside the if is not run.
Solution: you will get the expected behavior by supplying for with a row vector, not a column vector, e.g.:
H = 1:4;
for k = H
G = 3-k;
if G < 0
disp('break!')
break
end
end
3 commentaires
Stephen23
le 24 Juin 2020
"But it doesn't stop the loop when the codition (G < 0) is met"
It does when I run it, the code prints
break!
in the command window and the value of G is:
>> G
G = -1
As you did not show the code that you are using I cannot diagnose why it is not working. Note that if you want to avoid processing negative values, then your code will need to follow the break, i.e.:
H = 1:4;
for k = H
G = 3-k;
if G < 0
disp('break!')
break
end
... your code here!
end
Only then will you avoid proccessing the negative value.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!