Can I use if ..break...else inside the same loop?

조회 수: 5 (최근 30일)
Bee
Bee 2015년 10월 21일
편집: Bee 2015년 10월 26일
My apology if it seems very trivial to all, but I have looked into the answers and could not find one single example which used if..break...else in the same loop. In my code, I want the value of t, where any of the variables x(t) or y(t) or z(t).... equals M (some pre set value) for the first time and then discontinue the iteration; otherwise it will return 0. So my code snippet looks like:
for i = 1:T
...
...
if x(t) == M || y(t) == M || z(t) == M || a(t) == M || b(t) == M
target = t;
break
else
target = 0;
end
end
I got some suspicious answers, so I was thinking whether the problem is in the use of break or the random probabilities I used in my code. Thanks.
  댓글 수: 2
per isakson
per isakson 2015년 10월 21일
편집: per isakson 2015년 10월 21일
  • The use of break looks ok!
  • "I got some suspicious answers". How come "suspicious" ?
Bee
Bee 2015년 10월 22일
편집: Bee 2015년 10월 22일
Dear _ _per isakson,__thanks for your comments. The word 'suspicious' has a story - I was looking into the occurrence of consensus in a scale-free network and got some reasonable points of consensus; but after some tweaks here and there to change the simulation scenario, I am getting consensus even with a large population having varying opinions - this is 'suspicious' to me, because reaching consensus in a large network is fairly impossible.
However, I am happy that I used if..break..else correctly, so the 'suspicious' results must have something to do with the probabilities of opinion updates or network structure.

댓글을 달려면 로그인하십시오.

채택된 답변

Robert
Robert 2015년 10월 21일
편집: Robert 2015년 10월 22일
Your code looks fine. However, you can simplify the structure by adding target = 0; before your loop and omitting the else statement.
You might also consider using find(X==M,1), replacing X with each of your variables and then using min to find the index of the first occurrence of M, equivalent to your iterator i when you hit the break statement.
In any case, your use of if...break...else is not incorrect.
  댓글 수: 4
Guillaume
Guillaume 2015년 10월 22일
A possibly more efficient way of achieving the same result:
target = find(any([x;y;z;a;b] == M), 1); %assuming x,y,etc. are row vectors.
Less to type anyway.
Bee
Bee 2015년 10월 26일
편집: Bee 2015년 10월 26일
Thanks a bunch Guillaume, I was looking for something like this; I didn't know how to use 'any' in the code. Your suggestion is awesome :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by