Preface > Monte Carlo Simulation Basics > Matlab Example

Monte Carlo Simulation in Matlab

Supplement to: "Guide to Monte Carlo Simulation in Excel"
Normal Distribution Curve

I'll have to admit that I don't always use Excel for Monte Carlo simulation. If you don't have a Monte Carlo add-in for Excel, running a simulation with over 100000 points is not very practical. I usually use Matlab in that case (which is likely available somewhere on campus, if you are attending a university).

The trick to using Matlab for Monte Carlo simulation is to avoid using loops, since loops are particularly slow in Matlab. The example m-file below uses element-wise vector multiplication instead of loops. You don't need the Statistics Toolbox to use this code.

For more information about how Monte Carlo simulation works, please read "Monte Carlo Simulation in Excel: A Practical Guide".


% Example Monte Carlo Simulation in Matlab
% Function: y = x2^2/x1
%
%   Generate n samples from a normal distribution
%     r = ( randn(n,1) * sd ) + mu
%     mu : mean
%     sd : standard deviation
%
%   Generate n samples from a uniform distribution
%     r = a + rand(n,1) * (b-a)
%     a : minimum
%     b : maximum

n = 100000;	% The number of function evaluations

% --- Generate vectors of random inputs
% x1 ~ Normal distribution N(mean=100,sd=5)
% x2 ~ Uniform distribution U(a=5,b=15)

x1 = ( randn(n,1) * 5 ) + 100;
x2 = 5 + rand(n,1) * ( 15 - 5 );

% --- Run the simulation
% Note the use of element-wise multiplication

y = x2.^2 ./ x1;

% --- Create a histogram of the results (50 bins)

hist(y,50);

% --- Calculate summary statistics

y_mean = mean(y)
y_std = std(y)
y_median = median(y)

[ Monte Carlo Simulation ]Previous Topic    


REFERENCES:

Huber, T., "Introduction to Monte Carlo Simulation", http://physics.gac.edu/~huber/envision/instruct/montecar.htm

The Matlab Central File Exchange, Statistics and Probability, http://www.mathworks.com/matlabcentral/



CITE THIS PAGE AS:

Wittwer, J.W., "Monte Carlo Simulation in Matlab" From Vertex42.com, November 11, 2004, http://vertex42.com/ExcelArticles/mc/MatlabMCExample.html

 

INDEX (This Article)
Preface and Software
Monte Carlo Simulation
Deterministic Model
Stochastic Model
Sales Forecast Example
Random Inputs
Histograms
Summary Statistics
Percentiles
Normal Distribution
Matlab Example

ABOUT THIS SITE
About the Author
Terms of Use
Privacy

DESTINATIONS
The Excel Nexus (Links)
Excel Calendar Template
Excel Timesheet
Free Excel Templates

 

Monte Carlo Simulation in DFSS
Features:
- Monte Carlo Simulation
- Design for Six Sigma
- Robust Design
- Tolerance Allocation

© 2004 Vertex42, LLC "Monte Carlo Simulation in Matlab"