Generating random numbers from a piecewise probability distrubution in matlab
I am trying to input the following piecewise function into matlab as a probability distribution. Then I'm trying to generate 开发者_StackOverflow中文版random values of X. I have the statistic tool box so I can generate the random numbers using that, but I cannot figure out how to input the function so that I can actually generate the random numbers.
P(X)= Ax 0<=x<1
A/2 1<=x<2
0 otherwise
A is a normalization constant.
I ultimately want to show a histogram of 10,000 trials from this distribution and find the mean and standard deviation of my simulation.
samples from given distribution can be generated for instance using inverse transform sampling (see http://en.wikipedia.org/wiki/Inverse_transform_sampling) It's quite easy since you just generate uniformly distributed values and then compute inverse of your cumulative distribuition function
Cumulative distrib. function can be computed by integration of propability density function, in your case
x^2/2 ... x from <0,1>
x/2 ... x from (1,2>
Note, that the normalizing constant is A=1 now, the m-file doing this is the following
function vals =genDist(len)
vals = rand(len,1);
for i=1:length(vals)
if vals(i)<=1/2 % vals(i) 0..0.5
vals(i) = sqrt(2*vals(i));%inverse function of x^2/2
else % vals(i) 0.5-1
vals(i) = vals(i)*2; %inverse function of x/2
end
end
end
精彩评论