How to genarate a random variable in matlab with density function f(x)=x/2 for 0<=x<=2 and f(x)=0 otherwise

13 views (last 30 days)
I am new to matlab and want to generate a random variable that has probability density function as
f(x)=x/2 ,0<=x<=2 0 ,otherwise
I understand that given pdf is not already defined in matlab .

Answers (1)

Star Strider
Star Strider on 26 Sep 2014
Edited: Star Strider on 26 Sep 2014
This seems to work:
pdfx = @(x) 2*sqrt(x); % Define PDF
x = rand(1,100000); % Generate Random ‘x’
px = pdfx(x); % Generate Data
bins = linspace(0,2,100); % Define ‘bins’ For ‘histc’
pdx = histc(px,bins); % Histogram
figure(1)
bar(bins, pdx/sum(pdx)) % Plotted Histogram

Categories

Find more on Random Number Generation in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!