MathGroup Archive 2008

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

Search the Archive

Re: Variable amount of Buttons in Mathematica

  • To: mathgroup at
  • Subject: [mg92851] Re: Variable amount of Buttons in Mathematica
  • From: magma <maderri2 at>
  • Date: Wed, 15 Oct 2008 05:37:09 -0400 (EDT)
  • References: <gcscrf$8l3$> <gcv77d$ds9$>

On Oct 13, 12:17 pm, "sjoerd.c.devr... at"
<sjoerd.c.devr... at> wrote:
> It can be done with:
> array = {1, 2, 3, 4, 5};
> Row[Table[
>   With[{n = n},
>    Button[array[[n]], Print[n], ImageSize -> {50, 50}]], {n, 1,
>    Length[array], 1}]]
> This uses the somewhate puzzling With[{n = n} construction, which
> replaces every occurance of the *variable* n (which doesn't make sense
> after the Table command has finished) with the succesive *values* it
> had during the table execution.
> Cheers -- Sjoerd

Indeed Sjoerd, it is a very puzzling construct especially for a
newcomer like SDY.
I was amazed to see that all the "With" answers used n=n .
If this were a class exercise I would have suspected copying :-)
Then Eric mentioned that this was shown in the Button documentation
(they use i=i).
Ah, ah, so it was indeed copying :-)

The point is: n=n is not necessary and frankly not recommended.
MMA syntax colouring shows the 2 n's with slightly different colours,
but it is hard to tell and not very illuminating for a newbie.

I would suggest the following syntax:

 array = {1, 2, 3, 4, 5};
   Table[With[{k = n},
     Button[array[[k]], Print[k], ImageSize -> {50, 50}]], {n,

where I use With[{k=n}, .....
Here the concept is clearer: each element in the table is built using
the "With-local" k.
In turn, k takes the current value of the "Table-looping" n.

  • Prev by Date: Re: Why is this integral hard for mathematica?
  • Next by Date: Re: Exclude O[] from Series[] for Solve[] in Mathematica
  • Previous by thread: Re: Variable amount of Buttons in Mathematica
  • Next by thread: Re: Re: Variable amount of Buttons in Mathematica