MATLAB Answers

Break command doesn't stop the For loop

6 views (last 30 days)
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 Comments

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 24 Jun 2020
Edited: Stephen Cobeldick on 24 Jun 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 Comments

Ketan Patel
Ketan Patel on 24 Jun 2020
Hello Stephen,
Thank you so much for your reply.
I tried you code. But it doesn't stop the loop when the codition (G < 0) is met. I am trying to find out a way to substract a value from an array, while collecting the new values inot another array, and stop the operation as soon a value reaches a negative value. So, I have a new array (G) with only the positive values.
I hope the explanation is clear.
Thank you!
Stephen Cobeldick
Stephen Cobeldick on 24 Jun 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.
Ketan Patel
Ketan Patel on 24 Jun 2020
Oh, I see. I think i know what i am doing wrong.
Thank you for taking your time for answering to my question.

Sign in to comment.

More Answers (0)


Translated by