Clear Filters
Clear Filters

Monte Carlo Simulation with Parfor

1 view (last 30 days)
Jonathan
Jonathan on 30 Jul 2015
Commented: Walter Roberson on 30 Jul 2015
I am conducting a Monte Carlo simulation of a stochastic differential equation, and trying to parallelize each random walk. Take a simplified example:
parfor j=1:N
for i=2:M
W(j,i) = W(j,i-1) + N(j,i);
end
end
Matlab complains because it can't slice W(j,i-1) because of the 'i-1' indexing. To me, this seems silly because I am still not doing anything that couples each iteration of the parfor (each iteration of parfor works on a separate row).
Is there a way around this that is hopefully elegant and simple?

Answers (1)

Walter Roberson
Walter Roberson on 30 Jul 2015
parfor j=1:N
W(j,:) = W(j,:) + cumsum([0, N(j,:)]));
end
I am presuming here that the N of the "parfor" is some variable different than the "N" that is indexed.
If you are working with a subset of the row then:
W(j,:) = W(j,:) + [cumsum([0, N(j,1:M)], zeros(1,size(N,2)-M)]
If this code is all there is to it, do the whole incrementing by array operations:
[rows, cols] = size(W);
W = W + [cumsum(zeros(rows,1), N(:,1:M)],2), zeros(rows, cols-M-1)];
The more general solution to the problem in the way expressed is
parfor j=1:N
thisrow = W(j,:);
thisN = N(j,:);
for i=2:M
thisrow(i) = thisrow(i-1) + thisN(i);
end
W(j,:) = thisrow;
end
  1 Comment
Walter Roberson
Walter Roberson on 30 Jul 2015
Thinking again:
parfor j=1:N
W(j,:) = cumsum([W(j,1), N(j,:)]);
end
and appropriate corrections to the other versions. For example,
W = cumsum([W(:,1), N],2);

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!