MathGroup Archive 2000

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

Search the Archive

Re: need little help

  • To: mathgroup at smc.vnet.net
  • Subject: [mg23541] Re: [mg23530] need little help
  • From: Andrzej Kozlowski <andrzej at tuins.ac.jp>
  • Date: Sat, 20 May 2000 03:10:19 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

If you agree with the principle (which I think, on the whole, is a good one)
that if something is already in a package included with  Mathematica then
one should use it,  you may prefer the following:

<< Statistics`MultiDiscreteDistributions`

In[2]:=
randomIndexPick[m_List] :=
  First[Flatten[Position[Random[MultinomialDistribution[1, m]], 1]]]

In[3]:=
Table[ randomIndexPick[ {0.2, 0.4, 0.1, 0.3} ], {20} ]
Out[3]=
{2, 4, 2, 2, 3, 1, 1, 2, 3, 1, 3, 2, 2, 4, 1, 4, 4, 4, 1, 4}



-- 
Andrzej Kozlowski
Toyama International University
JAPAN
http://sigma.tuins.ac.jp/
http://platon.c.u-tokyo.ac.jp/andrzej/


on 5/17/00 11:30 AM, Wagner Truppel at wtruppel at uci.edu wrote:

> Howdy everyone,
> 
> I have a list of probabilities (whose sum is 1.0), each associated
> with an index. I'd like to randomly choose an index based on those
> probabilities. For example, suppose
> 
> m = {0.2, 0.4, 0.1, 0.3}
> 
> which dictates that index 1 should be selected with prob 0.2, index 2
> with prob 0.4, index 3 with prob 0.1, and index 4 with prob 0.3.
> 
> I've already written a function that works, but I think there should
> be a simpler, more elegant, and more efficient way of accomplishing
> this task.
> 
> Here's my solution:
> 
> randomIndexPick[ m_ ] :=
> Module[ { r, s },
> r = Random[];
> s = Sort[ Thread[ { m, Range[ Length[m] ] } ] ];
> s = Table[ { Sum[ s[[i, 1]], { i, 1, k } ], s[[k, 2]] },
> { k, 1, Length[m] } ];
> s = Map[ ( { r ¾ First[#], Last[#] } ) &, s ];
> s = Select[ s, ( First[#] ) & ];
> Return[ s[[1, 2]] ] ];
> 
> Table[ randomIndexPick[ {0.2, 0.4, 0.1, 0.3} ], {20} ]
> 
> {4, 4, 1, 2, 2, 4, 4, 1, 4, 4, 2, 3, 1, 2, 2, 2, 4, 3, 2, 3}
> 
> Does anybody have a better solution?
> 
> Thanks!
> Wagner
> 



  • Prev by Date: Fit and InverseLaplaceTransform
  • Next by Date: Re: need little help
  • Previous by thread: Re: need little help
  • Next by thread: Re: need little help