Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2005
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

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

Search the Archive

Re: For Loop and Array related

  • To: mathgroup at smc.vnet.net
  • Subject: [mg58006] Re: For Loop and Array related
  • From: "Carl K. Woll" <carlw at u.washington.edu>
  • Date: Thu, 16 Jun 2005 05:36:09 -0400 (EDT)
  • Organization: University of Washington
  • References: <d8oucl$t6q$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

<mchangun at gmail.com> wrote in message news:d8oucl$t6q$1 at smc.vnet.net...
> 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.
>

Here's how I would approach this. Create a table of your random integers:

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

Then, the following function will create your lattice:

rand[d_] :=
 Normal[SparseArray[#[[All, 1]] -> Length /@ #, 100]] &[Split@Sort@d]

Apply the function rand to your data:

lattice=rand[data];

Check:

In[20]:=
Total[lattice]
Dimensions[lattice]
Out[20]=
16000
Out[21]=
{100}

Carl Woll
Wolfram Research 



  • Prev by Date: Re: Plot difficulties <Error Machine Sized Real Number>
  • Next by Date: field line with NDSolve
  • Previous by thread: Re: For Loop and Array related
  • Next by thread: Re: For Loop and Array related