do monte carlo simulation with correlation in matlab

To perform a Monte Carlo simulation with correlation in MATLAB:

  1. Define the means and standard deviations of the variables in the simulation.
main.m
% means and standard deviations of x and y
mu_x = 5;
sigma_x = 1;
mu_y = 10;
sigma_y = 2;
90 chars
6 lines
  1. Generate a specified number of random samples for each variable using normrnd function.
main.m
% generate 1000 random samples for x and y
n = 1000;
x_samples = normrnd(mu_x, sigma_x, n, 1);
y_samples = normrnd(mu_y, sigma_y, n, 1);
137 chars
5 lines
  1. Create a correlation matrix that specifies the correlation between x and y.
main.m
% correlation matrix
corr_xy = 0.7;
corr_matrix = [1 corr_xy; corr_xy 1];
74 chars
4 lines
  1. Generate correlated random variables using mvnrnd function.
main.m
% generate correlated random variables using mvnrnd function
correlated_samples = mvnrnd([mu_x mu_y], [sigma_x^2 corr_xy*sigma_x*sigma_y; corr_xy*sigma_x*sigma_y sigma_y^2], n);
x_samples = correlated_samples(:,1);
y_samples = correlated_samples(:,2);
252 chars
5 lines
  1. Repeat the simulation multiple times to estimate the distribution of a specified function of x and y.
main.m
% repeat simulation 100 times
num_simulations = 100;
z_samples = zeros(n,num_simulations);
for i = 1:num_simulations
    % generate correlated random variables using mvnrnd function
    correlated_samples = mvnrnd([mu_x mu_y], [sigma_x^2 corr_xy*sigma_x*sigma_y; corr_xy*sigma_x*sigma_y sigma_y^2], n);
    x_samples = correlated_samples(:,1);
    y_samples = correlated_samples(:,2);
    % calculate z as a function of x and y
    z_samples(:,i) = 2*x_samples - 3*y_samples;
end
480 chars
12 lines
  1. Visualize the distribution of the function using histogram function.
main.m
% plot histogram of z_samples
histogram(z_samples)
51 chars
3 lines

gistlibby LogSnag