Created
August 22, 2014 20:02
-
-
Save tinybike/6f8c41a2136212f2a3c1 to your computer and use it in GitHub Desktop.
random numbers from arbitrary probability distribution functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function f = randarbmulti(x,y,N) | |
% RANDARBMULTI generates N random numbers from an arbitrary PDF, defined by | |
% vectors x and y. Modified from randarb.m (Dave Dykes) at: | |
% http://www.mathworks.com/matlabcentral/fileexchange/6506-obs-from-arbitrary-pdf | |
% | |
% (c) Jack Peterson ([email protected]), 4/21/2013 | |
cdf_y = cumsum(y); | |
sum_y = sum(y); | |
f = zeros(N,1); | |
for j = 1:N | |
% Compute a uniform random number between 0 and sum(y) | |
randx = sum_y*rand(); | |
% Find where the number lies on a conceptual line comprised of "segments" of | |
% length y | |
i = 1; | |
while cdf_y(i) < randx | |
i = i + 1; | |
end | |
% Return the x value corresponding to the y value we "landed on." | |
f(j) = x(i); | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment