MathGroup Archive 2000

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

Search the Archive

Re: need little help

  • To: mathgroup at smc.vnet.net
  • Subject: [mg23556] Re: need little help
  • From: Martin Harborth <Martin.Harborth at vt.siemens.de>
  • Date: Sat, 20 May 2000 03:10:31 -0400 (EDT)
  • Organization: Siemens AG, ATD TD IT MV 1
  • References: <8ft164$m5r@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Werner,

I work with Version 4.0. Here is a shorter solution with the aid of a
standard add-on package:

<< Statistics`MultiDiscreteDistributions`
mnD[n_, p_] := MultinomialDistribution[n, p]
randomIndexPick[m_] := Position[Random[mnD[1, m]], 1][[1, 1]]

Table[randomIndexPick[{0.2, 0.4, 0.1, 0.3}], {20}]

{4, 3, 1, 2, 2, 3, 2, 1, 1, 2, 4, 4, 3, 2, 4, 1, 4, 2, 4, 2}



Bye the way, your solution does not work on my computer, the output is

Table[randomIndexPick[{0.2, 0.4, 0.1, 0.3}], {20}]
Part::"partw": "Part 1 of {} does not exist."
General::"stop": "Further output of \!\(Part :: \"partw\"\) will be \
suppressed during this calculation."


Bye, Martin.

Wagner Truppel schrieb:
> 
> 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: Re: need little help
  • Next by Date: Reply to
  • Previous by thread: Re: need little help
  • Next by thread: Mathematica crashing, short cut keys