Message Boards Message Boards

0
|
9626 Views
|
7 Replies
|
1 Total Likes
View groups...
Share
Share this post:
GROUPS:

Break nested loops

Posted 9 years ago

How can I exit multiple nested loops? Break[] exits nearest loop only.

For[j = 1, j <= 10, j++,
  For[i = 1, i <= 10, i++,
   If[i == 3 && j == 4, Break[]]
   ]];
Print[i, j]
POSTED BY: Al Guy
7 Replies

Throw and Catch.

But perhaps you would like to move away from ancient procedural programming constructs. And things like Break, Return, GoTo, and so on are the stuff of original Fortran and Basic.

POSTED BY: David Reiss

Abort?

POSTED BY: Isaac Abraham
Posted 9 years ago

That will terminate whole computation, not just exit the nested loop.

POSTED BY: Al Guy
Posted 9 years ago

Thanks. What's the reason the commands you mentioned aren't as good as Throw Catch?

POSTED BY: Al Guy

It is not that those commands are not good but those commands were put in Mathematica version one so that people coming from a strictly procedural background dating all the way back to the beginning of Fortran would have a simple entry point into Mathematica and then move on to the more powerful constructs of the wolfram language. In the Mathematica there is always a much clearer and more powerful approach using functional and rule-based programming.

POSTED BY: David Reiss
Posted 9 years ago

I had the same problem coming from basic and Fortran. That was procedural programming, so I was told... For loops: use Table, Nest, NestWhile, Fold, etc instead of For-Next. This is functional programming. Interrupt your "loops" by enclosing your code in a Catch and exit with Throw. It is a new habit but you learn it fast, it is faster and clear. Here is an example based on yr old style code:

In[9]:= Catch[
 Table[Table[{i, j}; 
   If[i == 3 && j == 4, Throw[{i, j}]], {i, 10}], {j, 10}]]

Out[9]= {3, 4}
POSTED BY: Erik Mahieu

(how to delete the post? :))

POSTED BY: Kuba Podkalicki
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract