Break command doesn't stop the For loop

4 ビュー (過去 30 日間)
Ketan Patel
Ketan Patel 2020 年 6 月 24 日
コメント済み: Ketan Patel 2020 年 6 月 24 日
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

採用された回答

Stephen23
Stephen23 2020 年 6 月 24 日
編集済み: Stephen23 2020 年 6 月 24 日
"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 件のコメント
Stephen23
Stephen23 2020 年 6 月 24 日
"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 2020 年 6 月 24 日
Oh, I see. I think i know what i am doing wrong.
Thank you for taking your time for answering to my question.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by