Run for loop 1000 times and get distribution of results
42 ビュー (過去 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 日 7:08
編集済み: Stephen23
2025 年 1 月 21 日 8:00
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 日 13:48
編集済み: Torsten
2025 年 1 月 21 日 14:06
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 日 5:29
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 で Histograms についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!