I have a code line having two Do
loops, one within other. In certain situation arising within inner loop, I want the outer Do
loop to break. How to achieve it ?
Here is a simplified example.
X = {{-10, 1, 1}, { 8, 2, 2}, {-7, 3, 1}, {2, 4, 2}};
XX = Reap[
Do[Do[If[X[[k, 1]] < 0, R = m*X[[k, 2]]; Sow[R], R = m*X[[k, 3]];
Sow[R]], {k, 1, 4}], {m, 1, 5}]][[2]]
The o/p of this code is
{{1, 2, 3, 2, 2, 4, 6, 4, 3, 6, 9, 6, 4, 8, 12, 8, 5, 10, 15, 10}}
Now for example, the element "9" appears in the o/p for the m = 3 cycle. I want to break the m loop for the next value of m as soon as "9" appears in the o/p. So in this case, the m cycle should stop at m = 3 instead of going up to 5. The o/p in that case should be
{{1, 2, 3, 2, 2, 4, 6, 4, 3, 6, 9, 6}}
I tried the beard combination of Break & Catch/Throw as shown below, but not able to make it work.
X = {{-10, 1, 1}, { 8, 2, 2}, {-7, 3, 1}, {2, 4, 2}};
XX = Reap[
Do[Catch[
Do[If[X[[k, 1]] < 0, R = m*X[[k, 2]]; Sow[R];
If[R == 9, Throw[Break[]]], R = m*X[[k, 3]];
Sow[R]]; If[R == 9, Throw[Break[]]], {k, 1, 4}]], {m, 1,
5}]][[2]]
Will appreciate any help.
thanks
Return
. If that does not do what is required, post a minimal working example and explain what exactly you want. $\endgroup$Do
since the number of inner loops doesn't depend on the outer loop. Then anything (Break[]
,Return[..., Do]
,Throw/Catch
) will work. $\endgroup$Throw[Break[]]
is a strange construct. What should it achieve? Why don't you useThrow
with a normal argument? $\endgroup$