Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: How to generate a random data?
Date: Fri, 27 Jul 2007 06:58:52 +0000 (UTC)
Organization: Universit&#228;t Stuttgart
Lines: 58
Message-ID: <f8c53c$8jt$1@fred.mathworks.com>
References: <ef5ede4.-1@webcrossing.raydaftYaTP> <f8bujg$6n6$1@fred.mathworks.com> <f8bvhp$jqd$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-00-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1185519532 8829 172.30.248.35 (27 Jul 2007 06:58:53 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Fri, 27 Jul 2007 06:58:52 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 545430
Xref: news.mathworks.com comp.soft-sys.matlab:421335



It think this function is faster:

function states = randomstate(probs, M, N)
%RANDOMSTATE  Randomly choose a state from given discrete probabilites.
%		X = RANDOMSTATE(PROBS) gives a random state from the discrete
%		probability distribuation given in vector PROBS.
%
%		X = RANDOMSTATE(PROBS, M, N) returns an N-by-M-matrix of random states.
%
%		For example, RANDOMSTATE([0.1 0.5 0.4]) is 1 with a probability of
%		0.1, 2 with a probability of 0.5 and 3 with a probability of 0.4
%
%		Note: The probability vector may contain weight values that are not
%		normalized to one.
%
%		Markus Buehren		

nOfStates = length(probs);
% sumProbs = sum(probs);

if nargin == 1
	M = 1;
	N = 1;
elseif nargin == 2
	N = M;
end

% Find states
if M == 1 && N == 1
	
	sumProbs = sum(probs);
	number = rand(1) * sumProbs;
	threshold = 0;
	for k = 1:nOfStates
		threshold = threshold + probs(k);
		if number <= threshold
			states = k;
			return
		end
	end
	states = nOfStates;	
	
	% this version is slower:
	%index = cumsum(probs);
	%states = find(rand(1) * index(end) < index, 1);
	
else
	
	sumProbs = sum(probs);
	numbers = rand(M,N) * sumProbs;
	states = ones(M,N);
	threshold = 0;
	for k = 1:nOfStates-1
		threshold = threshold + probs(k);
		states(numbers >= threshold) = k+1;
	end

end