57 views (last 30 days)

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.

Robert
on 21 Oct 2015

Edited: Robert
on 22 Oct 2015

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.

Robert
on 22 Oct 2015

You are welcome. In your question, you iterate over i = 1:T. Was that supposed to be t = 1:T? If so, your comment above is close, but not quite there. Also, I now see that your comment matches my suggestion, which also needs to be tweaked. I will update it so I don't mislead other readers who might not check the comments.

The find function looks for anything that evaluates to true (in other words anything but zero). If it is important to your code, check doc find to see what it does with nan. So to find values of N, we need to use

target = min([find(x==N,1), find(y==N,1), find(z==N,1)])

Guillaume
on 22 Oct 2015

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.

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

Start Hunting!
## 2 Comments

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/250213-can-i-use-if-break-else-inside-the-same-loop#comment_317902

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/250213-can-i-use-if-break-else-inside-the-same-loop#comment_317902

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/250213-can-i-use-if-break-else-inside-the-same-loop#comment_317939

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/250213-can-i-use-if-break-else-inside-the-same-loop#comment_317939

Sign in to comment.