Run for loop 1000 times and get distribution of results
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Stephen23
le 21 Jan 2025
Modifié(e) : Stephen23
le 21 Jan 2025
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 commentaires
Torsten
le 21 Jan 2025
Modifié(e) : Torsten
le 21 Jan 2025
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 ?
Plus de réponses (1)
Akshat Dalal
le 21 Jan 2025
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
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!