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일

1 개 추천

"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

Ketan Patel
Ketan Patel 2020년 6월 24일
편집: Ketan Patel 2020년 6월 24일
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!
"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개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2020년 6월 24일

댓글:

2020년 6월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by