Below is the partial code to plot the rejection/accept regions using monte carlo sampling. The context is to estimate pi and plotting is just one part of it.(adsbygoogle = window.adsbygoogle || []).push({});

I'm not sure how the ~ symbol can work.

I get the idea that ~ means "not". But reject is a different vector. How can the samples matrix detect logicals on vectors that aren't even subsets of the matrix?Code (Text):

scatter(samples(1,~reject),samples(2,~reject),'b.')

scatter(samples(1,reject),samples(2,reject),'rx')

The entire code and website I got it from is below.

https://theclevermachine.wordpress.com/2012/09/10/rejection-sampling/Code (Text):

% DISPLAY A CIRCLE INSCRIBED IN A SQUARE

figure;

a = 0:.01:2*pi;

x = cos(a); y = sin(a);

hold on

plot(x,y,'k','Linewidth',2)

t = text(0.5, 0.05,'r');

l = line([0 1],[0 0],'Linewidth',2);

axis equal

box on

xlim([-1 1])

ylim([-1 1])

title('Unit Circle Inscribed in a Square')

pause;

rand('seed',12345)

randn('seed',12345)

delete(l); delete(t);

% DRAW SAMPLES FROM PROPOSAL DISTRIBUTION

samples = 2*rand(2,100000) - 1;

% REJECTION

reject = sum(samples.^2) > 1;

% DISPLAY REJECTION CRITERION

scatter(samples(1,~reject),samples(2,~reject),'b.')

scatter(samples(1,reject),samples(2,reject),'rx')

hold off

xlim([-1 1])

ylim([-1 1])

piHat = mean(sum(samples.*samples)<1)*4;

title(['Estimate of \pi = ',num2str(piHat)]);

**Physics Forums | Science Articles, Homework Help, Discussion**

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

# MATLAB Sample Code for Monte Carlo estimation of pi

Have something to add?

Draft saved
Draft deleted

**Physics Forums | Science Articles, Homework Help, Discussion**