www.gusucode.com > stats 源码程序 matlab案例代码 > stats/GenerateRandomSamplesFromAMultimodalDensityExample.m

    %% Generate Random Samples From a Multimodal Density
% This example shows how to generate random samples from a multimodal
% density using |slicesample|.

% Copyright 2015 The MathWorks, Inc.


%%
% Define a function proportional to a multimodal density.
rng default  % For reproducibility
f = @(x) exp(-x.^2/2).*(1 + (sin(3*x)).^2).*...
    (1 + (cos(5*x).^2));
area = integral(f,-5,5);

%%
% Generate 2000 samples from the density, using a burn-in period of 1000,
% and keeping one in five samples.
N = 2000;
x = slicesample(1,N,'pdf',f,'thin',5,'burnin',1000);

%%
% Plot a histogram of the sample.
[binheight,bincenter] = hist(x,50);
h = bar(bincenter,binheight,'hist');
h.FaceColor = [.8 .8 1];

%%
% Scale the density to have the same area as the histogram, and superimpose
% it on the histogram.
hold on
h = gca;
xd = h.XLim;
xgrid = linspace(xd(1),xd(2),1000);
binwidth = (bincenter(2)-bincenter(1));
y = (N*binwidth/area) * f(xgrid);
plot(xgrid,y,'r','LineWidth',2)
hold off

%%
% The samples seem to fit the theoretical distribution well, so the
% |burnin| value seems adequate.