Parallel-izing, speeding up simulation
Afficher commentaires plus anciens
Hello,
I am trying to simulate a stochastic equation and empirically determine it's pdf. I have the following code,
NN=100;
ind = @(x) (x>0);
x_vect=zeros(NN,1001);
for j=1:NN
ts = 0.01;
x0=0;
x_vect(j,1)=x0;
if (mod(j,1000)==0)
rng('shuffle')
end
for i=1:100000
w = rand(1,1);
if ~(w < ts)
if (x0-2*ind(x0)*ts>0)
x_vect(j,i+1)=x0-2*ind(x0)*ts;
else
x_vect(j,i+1)=0;
end
else
x_vect(j,i+1)=x0+1;
end
x0=x_vect(j,i+1);
end
end
Each sample path should last for 1000 seconds (so the inner loop runs till 10000) and I need to do a total of NN=100000 sample paths. Currently this would take me about 7 hours to run the simulation. Does anyone see an obvious way to speed up the simulation and/or parallelize this code?
Réponse acceptée
Plus de réponses (1)
- x_vect is pre-allocated to the final size.
- anonymous function ind is replaced by direct comparison.
- x0 - 2 * (x0 > 0) * ts is calculated once only.
- x_vect accessed in columnwise order.
NN = 100;
ni = 100000;
x_vect = zeros(ni+1, NN);
for j=1:NN
ts = 0.01;
x0 = 0;
x_vect(j,1) = x0;
if mod(j,1000) == 0
rng('shuffle')
end
for i = 2:ni+1
w = rand;
if w >= ts
v = x0 - 2 * (x0 > 0) * ts;
if v > 0
x_vect(i, j) = v;
end
else
x_vect(i, j) = x0 + 1;
end
x0 = x_vect(i, j);
end
end
This give a boost from 35.1 sec to 0.60 sec on my machine. Now start experiments with parfor.
Catégories
En savoir plus sur Function Creation dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!