Clear Filters
Clear Filters

Hello, I wish for someone to help me explain (with a code example) how i can generate a random variable using Monte Carlo simulation.with loop for and if ,Am just a basic user of matlab,I will be grateful to get a response

2 views (last 30 days)
Hello, I wish for someone to help me explain (with a code example) how i can generate a random variable using Monte Carlo simulation.with loop for and if ,Am just a basic user of matlab,I will be grateful to get a response

Accepted Answer

Walter Roberson
Walter Roberson on 31 Aug 2020
N = 100000;
count = 0;
R = 5;
for K = 1 : N
r = R * rand(1,2);
if sqrt(r(1)^2 + r(2)^2) <= R
count = count + 1;
end
end
pi_approximation = 4 * (count / N);
  4 Comments
Walter Roberson
Walter Roberson on 31 Aug 2020
N = 10000;
hits = 0;
misses = 0;
R = 5;
subplot(1,2,1)
axes equal
h = animatedline('Linestyle', 'none', 'marker', '*');
for K = 1 : N
r = R * rand(1,2);
if sqrt(r(1)^2 + r(2)^2) <= R
hits = hits + 1;
addpoints(h,r(1), r(2));
if mod(count, 25); drawnow; end
else
misses = misses + 1;
end
end
pi_approximation = 4 * (count / N);
subplot(1,2,2)
bar([hits, misses]);
xticks([1 2]);
xticklabels({'hits', 'misses'});

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!