/************** SAMPLE FROM VECTOR **************************/ /* ** sample.src ** Author: Alan G. Isaac ** mailto:aisaac@american.edu ** Date: 21 May 2001 ** Caveat: this code is provided gratis but without ** any performance warrantee or guarantee. ** Comments welcomed. ** **> sample ** ** Purpose: sample from vector given associated probabilities ** ** Format: y = sample(x,p,n); ** ** Input: x K by 1 vector to be sampled from ** p K by 1 vector of sampling frequencies ** n integer: the sample size ** Output: y resulting sample ** ** Comments: If sumc(p) /=1, p will be normalized. ** Works if x is matrix: samples row-wise. ** Based on a suggestion by Scott Thompson. */ proc (1) = sample(x,p,n); local y,rp,userows; y={}; if cols(p)>1;"Put sampling frequencies in a column vector.";retp(y);endif; rp=rows(p); if rows(x) /= rp;"Rows don't match!";retp(y);endif; if sumc(p) /=1; "Warning: normalizing sampling frequencies."; p=p/sumc(p); endif; userows=1+sumc(rndu(1,n).>cumsumc(p)); y=x[userows]; retp(y); endp;