Message Boards Message Boards

0
|
8192 Views
|
5 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Localization of variables in For loop

Posted 6 years ago

Version: Mathematica 11.3.0.0 Platform: Windows 64

If I am not mistaken, there is a bug in the For loop implementation. If I am wrong, please correct me.

It looks like the loop variable is not localized properly. Consider:

test[n_] := Module[{}, If[n > 2, Return[]]; Do[Print[{i,n}];test[n+1],{i,2}] ]; test[1]

This works o.k., the output is: {1,1 } {1,2} {2,2} {2,1} {1,2} {2,2}

Now consider:

test[n_] := Module[{}, If[n > 2, Return[]]; For[i = 1, i <= 2, i++, Print[{i, n}]; test[n + 1]] ]; test[1]

Now the output is wrong: {1,1} {1,2} {2,2}

However, if one localizes the loop variable i in the module, it again works o.k.:

test[n_] := Module[{i}, If[n > 2, Return[]]; For[i = 1, i <= 2, i++, Print[{i, n}]; test[n + 1]] ]; test[1]

Now the output is again : {1,1 } {1,2} {2,2} {2,1} {1,2} {2,2}

POSTED BY: Daniel Huber
5 Replies

Do loops can often be replaced with Map.

POSTED BY: Frank Kampas

For loops and Do loops are inefficient in Mathematica. Better to use functions like Table.

POSTED BY: Frank Kampas

For loops and Do loops are inefficient in Mathematica. Better to use functions like Table.

There are many reasons to avoid the For loop in favor of the Do loop, outlined pretty well in this post, but I don't believe efficiency is one of the reasons. And the decision to use Table or Do is entirely up to whether you want to return a list of values or not - the same difference between Map and Scan.

People will often use the Do loop inefficiently, by first creating a list and then using AppendTo during each iteration, which is definitely inefficient. But if you just want to do something a certain number of times, then Do is the best way to go.

POSTED BY: Jason Biggs

For does not localize variables:

i = 1
For[, i < 5, i++, Print[i]]

is the same as:

For[i = 1, i < 5, i++, Print[i]]

Also i keeps its value after the For is done:

i =.
For[i = 1, i < 5, i++, Print[i]]
i

returns 5…

POSTED BY: Sander Huisman
Posted 6 years ago

For loops and Do loops are inefficient in Mathematica. Better to use functions like Table.

There are many reasons to avoid the For loop in favor of the Do loop, outlined pretty well in this post, but I don't believe efficiency is one of the reasons. And the decision to use Table or Do is entirely up to whether you want to return a list of values or not - the same difference between Map and Scan.

People will often use the Do loop inefficiently, by first creating a list and then using AppendTo during each iteration, which is definitely inefficient. But if you just want to do something a certain number of times, then Do is the best way to go.

POSTED BY: Daniel Huber
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