need little help
- To: mathgroup at smc.vnet.net
- Subject: [mg23530] need little help
- From: Wagner Truppel <wtruppel at uci.edu>
- Date: Tue, 16 May 2000 22:30:01 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
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
- Follow-Ups:
- Re: need little help
- From: Ken Levasseur <Kenneth_Levasseur@uml.edu>
- Re: need little help