MathGroup Archive 2005

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

Search the Archive

Re: For Loop and Array related

  • To: mathgroup at
  • Subject: [mg58015] Re: For Loop and Array related
  • From: Paul Abbott <paul at>
  • Date: Thu, 16 Jun 2005 06:43:50 -0400 (EDT)
  • Organization: The University of Western Australia
  • References: <d8oucl$t6q$>
  • Sender: owner-wri-mathgroup at

In article <d8oucl$t6q$1 at>,
 "mchangun at" <mchangun at> wrote:

> 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?

A syntax error (use of == vs. =) and a subtlety. Here is the modified 

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

I've included SeedRandom[1]; so that we get a "repeatable" random 

Note the use of the local variable t. If you write

  Lattice[[Random[Integer, {1, 100}]]]++ 

then, essentially, you are evaluating

  Lattice[[Random[Integer, {1, 100}]]] = 
    Lattice[[Random[Integer, {1, 100}]]] + 1

which involves two _different_ random numbers.

> 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?

First compute a list of 16000 numbers:

  SeedRandom[1]; t = Table[Random[Integer, {1, 100}], {16000}];

Here are three ways to compute Lattice:

[1] Count[t, #]& /@ Range[100]

[2] << "Statistics`"; 

    BinCounts[t, {0, 100}]

[3] Length /@ Split[Sort[t]]

These 3 codes give the same result as above.

The last code will not work with short lists because it does not return 
any zero counts.


Paul Abbott                                      Phone: +61 8 6488 2734
School of Physics, M013                            Fax: +61 8 6488 1014
The University of Western Australia         (CRICOS Provider No 00126G)    

  • Prev by Date: Re: Plot difficulties <Error Machine Sized Real Number>
  • 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