How to use mhsample or slicesample with ksdensity?

How can I set up the arguments for mhsample and/or slicesample so I can draw samples from a probability density function estimated using ksdensity? I have been unable to create a function handle for the target distribution "pdf" so that it will work with mhsample or slicesample. I want to use ksdensity to estimate a pdf, then draw samples from that pdf/distribution. The function handle "pdf" takes only one argument, but ksdensity requires two or more. Please advise me.

1 件のコメント

Darwin Brochero
Darwin Brochero 2012 年 9 月 19 日
I have the same question? Please advise me

サインインしてコメントする。

回答 (1 件)

Tom Lane
Tom Lane 2012 年 9 月 19 日

0 投票

Suppose you have data "mydata" and you want to base the ksdensity on that:
mydata = [randn(100,1); 6+randn(150,1)];
a1 = subplot(3,1,1);
[f,x,w] = ksdensity(mydata);
plot(x,f)
Then you can set up a pdf function that computes the density based on the sample in mydata, but at specified x values, and provide that to slicesample:
N = 1000;
mypdf = @(x) ksdensity(mydata,x);
tic, y = slicesample(5,N,'pdf',mypdf); toc
a2 = subplot(3,1,2);
ksdensity(y)
But I don't recommend doing that. The plain version of ksdensity is a mixture of little normal distributions with a specific width, centered at each data value. It's easier to just sample from that directly. Pick data values at random, add random noise, and you get the results much faster than you would by applying slicesample to a ksdensity-based density estimate.
tic
i = randi(length(mydata),N,1);
noise = w*randn(N,1);
z = mydata(i) + noise;
toc
a3 = subplot(3,1,3);
ksdensity(z)
set([a1 a2 a3],'XLim',[-10 15])
My tic/toc values were 10.634902 seconds vs. 0.001418 seconds.

タグ

質問済み:

2011 年 8 月 17 日

Community Treasure Hunt

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

Start Hunting!

Translated by