for loop matlab monte carlo in matlab

Here's an example of how to use a for loop in Matlab to carry out a Monte Carlo simulation. In this example, we will estimate the value of π by generating random points in a 2D square and counting how many of them fall inside a circle inscribed in the square.

main.m
% Define number of simulation runs and number of points per run
nRuns = 1000;
nPoints = 1000;

% Initialize counters for points inside and outside the circle
countInside = zeros(nRuns,1);
countOutside = zeros(nRuns,1);

% Loop over simulation runs
for i = 1:nRuns
    % Generate random points in the square
    x = rand(nPoints,1);
    y = rand(nPoints,1);
    
    % Count points inside and outside the circle
    countInside(i) = sum((x.^2 + y.^2) <= 1);
    countOutside(i) = nPoints - countInside(i);
end

% Estimate value of pi from the counts
piEstimate = 4 * mean(countInside ./ nPoints);

% Display result
disp(['Estimated value of pi: ' num2str(piEstimate)]);
669 chars
25 lines

In this code, we use a for loop to carry out nRuns independent simulations, each with nPoints random points generated using the rand function. For each run, we count how many of the points fall inside the unit circle (i.e., the circle with center at the origin and radius 1) and how many fall outside. We then use these counts to estimate the value of π using the formula:

π ≈ 4 * (number of points inside the circle) / (total number of points)

Finally, we display the estimated value of π using the disp function.

gistlibby LogSnag