Repeat simulation 300 times and plot all simulations in one graph

4 次查看(过去 30 天)
Hello
I've created a simulation, which I want to repeat 300 times, and the plot all the 300 simulations of the series in one graph. This is my code so far:
%script
X=rvdk;
a=9.5; %estimate value for a
b=0.4; %estimate value for b
c=0; %estimate value for c
d=159.7; %estimate value for d
T=257; %number of iterations (equals the number of observations in X)
lambda=montecarlo(X,a,b,c,d,T);
My function montecarlo looks like this:
function lambda=montecarlo(X,a,b,c,d,T)
i=1:T;
y0=1;
lambda0=0;
X0=0.0044;
lambda(1)=a+b.*y0+c.*lambda0+d.*X0;
for i=1:T;
y(i)=poissrnd(lambda(i));
lambda(i+1)=a+b.*y(i)+c.*lambda(i)+d.*X(i);
end
Now I want to carry out the montecarlo function 300 times resulting in 300 series of 257 observations (since X has 257 observations) and then I want to plot all these series in the same graph. How is this done? I've tried using nested loops, but that hasn't gotten me nowhere.
I look forward to hear from you

采纳的回答

Adam
Adam 2014-11-7
编辑:Adam 2014-11-7
What have you tried with nested loops? It should just be a case of wrapping the relevant part of your code up in a loop (maybe just the call to montecarlo if the parameters don't change) something like this:
lambda = zeros(300,257);
figure; hAxes = gca;
hold( hAxes, 'on' )
for i = 1:300
lambda(i,:) = montecarlo(X,a,b,c,d,T);
plot( hAxes, lambda(i,:) );
end
  4 个评论
Adam
Adam 2014-11-7
编辑:Adam 2014-11-7
Are you sure you put my code in the right place? It should only create a single figure as the figure creation is outside the for loop.
I didn't test with your actual montecarlo function, I just used rand(257,1) in it's place for my test as I don't have whatever rvdk is.
You can avoid plotting in the for loop actually though and just do:
lambda = zeros(300,257);
for i = 1:300
lambda(i,:) = montecarlo(X,a,b,c,d,T);
end
figure; plot( lambda.' );
I simplified the plotting instruction, although personally I would favour a two liner:
figure; hAxes = gca;
hLines = plot( hAxes, lambda.' );
but that is just because I prefer plotting onto an explicit axes, especially if I may want the axes again in the future. hLines will be a length 300 array of line objects in case you need to manipulate those.
Kristoffer
Kristoffer 2014-11-7
I accidentally had some code in the bottom of the script, which resulted in a infinite recursion. I've fixed it now and your code works perfectly! Thanks a lot for your help.

请先登录,再进行评论。

更多回答(1 个)

Prashant Arora
Prashant Arora 2020-5-13
lambda = zeros(300,257);
figure; hAxes = gca;
hold( hAxes, 'on' )
for i = 1:300
lambda(i,:) = montecarlo(X,a,b,c,d,T);
plot( hAxes, lambda(i,:) );
end

类别

Help CenterFile Exchange 中查找有关 Line Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by