Run for loop 1000 times and get distribution of results
7 次查看(过去 30 天)
显示 更早的评论
I have some code that runs a simulation of an equation in a for loop which results in a 1x128 array. I want to run a large number of these simulations, say 1000, so we have 1000 arrays of 1x128, then get the distribution of the 128th element of each array, say in a histogram.
So run for loop 1000 times, take value of 128th column from each array for 1000 values, then plot histogram of results. The X axis would be 0 to 1 and the Y axis would be frequency of each value (of course).
I'm sure the solution is quite simple, but everything I've tried hasn't worked right and I can't figure out where I'm going wrong, so I'd appreciate some advice.
Xzero = 0;
T = 1;
N = 2^8;
dt = 1/N;
r=1;
G=0.7;
e=0.5;
M=1000;
dW = sqrt(dt)*randn(M,N);
W = cumsum(dW);
R = 2; Dt = R*dt; L = N/R;
Xem = zeros(1,L);
Xtemp = Xzero;
for j = 1:L
Winc = sum(dW(R*(j-1)+1:R*j));
Xtemp = Dt*r*(G-Xtemp) + sqrt((e*Xtemp)*(1-Xtemp))*Winc;
Xem(j) = Xtemp;
end
0 个评论
采纳的回答
Stephen23
2025-1-21
编辑:Stephen23
2025-1-21
T = 1;
N = 2^8;
dt = 1/N;
r = 1;
G = 0.7;
e = 0.5;
R = 2;
Dt = R*dt;
L = N/R;
M = 1000;
Xem = nan(M,L);
for ii = 1:M
dW = sqrt(dt)*randn(M,N);
W = cumsum(dW);
Xtemp = 0;
for jj = 1:L
Winc = sum(dW(R*(jj-1)+1:R*jj));
Xtemp = Dt*r*(G-Xtemp) + sqrt((e*Xtemp)*(1-Xtemp))*Winc;
Xem(ii,jj) = real(Xtemp);
end
end
display(Xem)
3 个评论
Torsten
2025-1-21
编辑:Torsten
2025-1-21
You never use W, so why do you compute it as
W = cumsum(dW);
Further, dW is a 2d-array. Are you sure that accessing
dW(R*(jj-1)+1:R*jj)
thus converting 2d- to 1d-indexing here, is correct ?
If yes: shouldn't it be
Winc = sum(dW(M*(jj-1)+1:M*jj));
instead of
Winc = sum(dW(R*(jj-1)+1:R*jj));
?
Further taking the real part of the results Xem - do you think it's correct ?
更多回答(1 个)
Akshat Dalal
2025-1-21
Hi,
You can run the above code inside another for loop from 1 to 1000. In each iteration, you can store the value of the 128th column in another array defined outside the first loop. This way, you store only the desired value in each iteration. You can then plot the histogram on this array as necessary.
Thanks
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!