Are there any examples showing how to perform Monte Carlo simulation in MATLAB?
171 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
MathWorks Support Team
el 20 de En. de 2010
Comentada: Image Analyst
el 12 de Oct. de 2021
I would like to perform a Monte Carlo simulation in MATLAB and would like to see an example for this.
Respuesta aceptada
MathWorks Support Team
el 17 de Jun. de 2021
Editada: MathWorks Support Team
el 21 de Jun. de 2021
Here is a simple example function which computes the value of pi by generating uniformly distributed points inside a square of side length 1 and determining the fraction of those points which fall inside the circle. Four times that fraction will be an approximation to pi.
function mypi = approxpi(n)
% Input: n = number of points to generate
% Default is n = 1e6
% Larger values of n should perform better
if nargin < 1
n = 1e6;
end
% Generate uniformly distributed points in
% [0, 1] x [0, 1]
xy = rand(n, 2);
% Compute distance from (0.5, 0.5)
r = sqrt((xy(:,1)-0.5).^2+(xy(:,2)-0.5).^2);
% Count fraction of points within 1/2 unit of (0.5, 0.5)
frac = sum(r <= 0.5) / n;
% Since square has side 1, circle has radius (1/2)
% and should have area of pi*(1/2)^2
% frac is approximately pi/4 so pi is approximately 4*frac
mypi = 4*frac;
Another example on Monte Carlo Simulation using MATLAB can be found at:
1 comentario
Image Analyst
el 12 de Oct. de 2021
@Sahar Jolini just call it a bunch of times and use the built-in std() function:
numTrials = 1000;
n = 1e6;
mypi = zeros(1, numTrials); % Preallocate space.
for k = numTrials
% Get an estimate for pi.
mypi(k) = approxpi(n);
end
% Get the standard deviation of those estimates:
sd = std(mypi);
Más respuestas (1)
Image Analyst
el 12 de Oct. de 2021
For what it's worth, I'm attaching three of my Monte Carlo demos.
0 comentarios
Ver también
Categorías
Más información sobre Monte-Carlo en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!