MathGroup Archive 2005

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

Search the Archive

Re: For Loop and Array related

  • To: mathgroup at
  • Subject: [mg58001] Re: For Loop and Array related
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at>
  • Date: Thu, 16 Jun 2005 05:35:58 -0400 (EDT)
  • Organization: The Open University, Milton Keynes, England
  • References: <d8oucl$t6q$>
  • Sender: owner-wri-mathgroup at

mchangun at wrote:
> 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
> above?
> Thanks in advanced.

Using the *Random* function directly within an assignment where the 
indices are supposed to be the same on both side might not be a good 
idea! You will find below the same function written in a slightly more 
Mathematica way: a *Do* loop is used since the index is not used in the 
body of the program and the index is first computed and saved in a 
variable before being used by the following instruction that increments 
the value of the corresponding element. Also, avoid defining symbol 
names that begin by a capital letter.

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


Best regards,

  • Prev by Date: Re: Randomness Test
  • Next by Date: Re: Re: fitting multiple datasets
  • Previous by thread: Re: For Loop and Array related
  • Next by thread: Re: For Loop and Array related