844 views (last 30 days)

Adam Wyatt
on 31 Mar 2015

Your question is ill-defined.

Monte-Carlo simulations simply mean perform your simulation with varying inputs such that the inputs are chosen randomly. Better MC simulations use prior information / simulations to pick the next iteration.

Here is an example - given an input, the method passes if it is greater than 0.5, fails if it is less than or equal to 0.5.

function out = Test(in)

out = (in>0.5);

end

And to test it:

MCSim = arrayfun(@(inputs) Test(inputs), rand(100,1));

Adam Wyatt
on 1 Apr 2015

Your question is far too vague - you're basically saying solve my problem, but haven't actually said what the problem is.

Lets assume that you have a set of variables (load, material etc.) and you want to test the performance of your system for different variable values. The first question that arises is what distribution are your variables, are the uniformly distributed or normally distributed say. Lets assume you have 2 variables, var1 is uniformly randomly distributed and var2 is normally distributed, and you want to perform N tests.

Lets say you want to run N tests, set up N vectors for your variable values:

N = 1000;

var1 = var1_min + (var1_max-var1_min)*rand(N, 1);

var2 = var2_mean + var2_std*randn(N, 1);

result = arrayfun(MyTestFunction, var1, var2);

% Where

function ScalarResult = MyTestFunction(Scalar_Var1, Scalar_Var2)

...

end

Hope this helps, but if you're not more specific then we cannot help you much more than that.

You could for example use the parallel toolbox with parfor to help speed up your testing:

N = 1000;

var1 = ...

var2 = ...

result = zeros(N, 1);

parfor n=1:N

result(n) = MyTestFun(var1(n), var2(n));

end

Sign in to comment.

Image Analyst
on 31 Mar 2015

NURSAFIKA BAHIRA JULI
on 21 Jan 2020

Image Analyst
on 21 Jan 2020

You just did.

But I have no idea what langmuir isotherm is, so I can't help you with that.

Sign in to comment.

John D'Errico
on 31 Mar 2015

Most simply:

rand(1000,1)

What is the problem?

Edmar Adem
on 17 Jan 2018

John D'Errico
on 17 Jan 2018

Sign in to comment.

leichong lei
on 10 Apr 2019

Sign in to comment.

Sign in to answer this question.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Direct link to this comment

https://fr.mathworks.com/matlabcentral/answers/195421-how-to-write-a-monte-carlo-simulation-code#comment_360592

⋮## Direct link to this comment

https://fr.mathworks.com/matlabcentral/answers/195421-how-to-write-a-monte-carlo-simulation-code#comment_360592

Sign in to comment.