필터 지우기
필터 지우기

How to add the iteration count to the code

조회 수: 2 (최근 30일)
Ying
Ying 2012년 4월 12일
Hi,
I started using Matlab to run Monte Carlo Simulation just a few weeks ago. I have a question about the iteration count:
My code looks like this:
% Toll Road Brownian Motion Problem
% Set the initial parameters
mu=0.2;
sigma=0.1;
price=3;
n=35;
% Generate the initial traffic amount
R(1,1)=normrnd(10000,3000);
% Brownian Motion Iteration (Traffic)
for i=2:36
R=R.*exp((mu-sigma-0.5*sigma^2)*1+sigma*normrnd(0,1)*1);
end;
% Revenue Calculation (Revenue)
Revenue=price*R*365;
This code runs good except that since I generated random numbers, I would like to generate them for 1000 times, and get the average value out of all the 1000 simulations.
I wanted to add
for k=1:1000
But I don't know how my R matrix can interact with this extra k count.
I'd really appreciate it someone could offer a bit of advice.
Thanks a lot.
Ying

채택된 답변

Sargondjani
Sargondjani 2012년 4월 12일
you could make a R into a row vector (this will be faster than looping over k)
N=1000; %number of simulations
R=normrnd(10000,3000,[1,N]);
for i=2:36
R=R.*exp((mu-sigma-0.5*sigma^2)*1+sigma*normrnd(0,1,[1,N])*1);
end
This should give you a row vector containing the R's for N simulations
  댓글 수: 1
Ying
Ying 2012년 4월 12일
Hi Sargondjani,
Thanks so much for your answer. I checked the size of R after using your above code, and it gave me a 1 by 10000 as opposed to 36 10000. I guess the i from 1 to 36 was not counted in the loop. So I went from this matrix representation and used the following code:
% Generate the traffic amount per day
N=10000; %number of simulations
for j=1:N
for i=1;
R(i,j)=norminv(rand(1,1),10000,3000); % Random Initial Traffic
end;
for i=2:36
R(i,j)=R(i-1,j).*exp((mu-sigma-0.5*sigma^2)*1+sigma*z*1);
end;
end;
Basically, I'm using the rows to represent different years (36 rows in total), and using the columns to represent different iterations (10000 in total), and this code works.
And you are right, this is much efficient than using the loop. Thanks a lot for providing a starting point and a really efficient way for simulation iterations.
Ying

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Sargondjani
Sargondjani 2012년 4월 12일
With a loop, you could it something like this:
for ik=1:N;
R(1,ik)=normrnd(10000,3000);
for it=2:36
R(1,ik)=R(1,ik).*exp((mu-sigma-0.5*sigma^2)*1+sigma*normrnd(0,1)*1);
end;
end;
And if you want to keep track of the changes in R then you could do:
R(it,ik)=R(it-1,ik).*exp((mu-sigma-0.5*sigma^2)*1+sigma*normrnd(0,1)*1);

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by