Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: local variables - Module, For loop

  • To: mathgroup at smc.vnet.net
  • Subject: [mg113060] Re: local variables - Module, For loop
  • From: "Sjoerd C. de Vries" <sjoerd.c.devries at gmail.com>
  • Date: Tue, 12 Oct 2010 04:27:50 -0400 (EDT)
  • References: <i8ukij$o9s$1@smc.vnet.net>

The For function differs from many other languages in that its
function is not restricted to initializing a variable, increasing it
end testing it for an end value.

In For[start,test,incr,body], start, incr, and body parts may actually
do anything you can dream of; it isn't restricted to working with a
single counting variable. start doesn't necessarily involve any
initializing and incr doesn't really have to involve increasing a
variable. the test should deliver a boolean to make sense, though.

Given this freedom, localizing a variable (which one then?) wouldn't
make sense and indeed you have to use Module or Block for that.

"Do" on the other hand localizes its loop variable, but its clearly
identifiable there and localizing makes sense in that case.

Cheers -- Sjoerd

On Oct 11, 11:14 am, Sebastian Schmitt <sschm... at physi.uni-
heidelberg.de> wrote:
> Dear all!
>
> (I recycle my disclaimer.)
>
> I'm new to Mathematica with a background mostly in C++. Many times I
> have the impression that my style is not natural-Mathematica
> (Mathematicaesque so to say).
>
> If I have a For loop in a function like this:
>
> In[39]:= f[x_] := Module[{},
>   For[i = 0, i != x, i++,
>    Print[i]
>    ]
>   ]
>
> In[41]:= f[2]
>
> During evaluation of In[41]:= 0
>
> During evaluation of In[41]:= 1
>
> In[42]:= i
>
> Out[42]= 2
>
> I was surprised to find "i" being not local to the For loop. Do I have
> to keep track of all my throw-away-variables and put them in the list of
> local variables of the Module? I find it pretty tedious. Is there a
> better way?
>
> Thanks in advance,
>
> Sebastian



  • Prev by Date: Re: C-pointers from Mathematica
  • Next by Date: Limitations of Minimize? Time to buy a new PC for Mathematica?
  • Previous by thread: Re: local variables - Module, For loop
  • Next by thread: Re: local variables - Module, For loop