MathGroup Archive 2005

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

Search the Archive

Re: For Loop and Array related

  • To: mathgroup at
  • Subject: [mg57999] Re: [mg57971] For Loop and Array related
  • From: "David Park" <djmp at>
  • Date: Thu, 16 Jun 2005 05:35:56 -0400 (EDT)
  • Sender: owner-wri-mathgroup at

I don't understand that.

Switching to a simpler Do statement, note that the following does not work.

Lattice = Table[0, {n, 100}];
Do[Lattice[[Random[Integer, {1, 100}]]]++, {16000}]

But if we calculate the index location first it does work.

Lattice = Table[0, {n, 100}];
Do[i = Random[Integer, {1, 100}]; Lattice[[i]]++,

If we do a Trace on the increment statement in the first construction we
obtain the following...

Lattice = Table[0, {n, 5}];
Trace[Lattice[[Random[Integer, {1, 5}]]]++]
{HoldForm[Lattice[[Random[Integer, {1, 5}]]]++],
  {{HoldForm[Lattice], HoldForm[{0, 0, 0, 0, 0}]},
   {HoldForm[Random[Integer, {1, 5}]], HoldForm[3]},
   HoldForm[{0, 0, 0, 0, 0}[[3]]], HoldForm[0]},
  {HoldForm[Lattice[[Random[Integer, {1, 5}]]] = 1],
   HoldForm[1]}, HoldForm[0]}
{0, 0, 0, 1, 0}

which I do not follow, but it appears that Mathematica is calculating the
random index twice.

David Park
djmp at

From: mchangun at [mailto:mchangun at]
To: mathgroup at

Hi All,

I have an array with 100 elements, all set to zero initially.  Then I
want to randomly choose one element and increase its value by one, and
repeat this 16000 times. Here is my code:

Lattice = Table[0, {n, 100}];
For[i = 1, i = 16000, i++, Lattice[[Random[Integer, {1, 100}]]]++]

So now if I add all the elements in the list Lattice together, I should
get 16000 (I use Total[Lattice] to get the sum of the list).  But this
doesn't happen, and strangely, each time I run this, the sum of the
list is different!  What am I doing wrong?

Also I'm aware that a lot of Mathematica newbies try and write code
like it were C++ and I think i've fallen into this trap as well.  So is
there a different (more Mathematica) way which I can implement the

Thanks in advanced.

  • Prev by Date: Transformation rule problem
  • Next by Date: Re: For Loop and Array related
  • Previous by thread: Re: For Loop and Array related
  • Next by thread: Re: For Loop and Array related