Run for loop 1000 times and get distribution of results
조회 수: 4 (최근 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!