Monte Carlo Simulation with Parfor

조회 수: 3 (최근 30일)
Jonathan
Jonathan 2015년 7월 30일
댓글: Walter Roberson 2015년 7월 30일
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?

답변 (1개)

Walter Roberson
Walter Roberson 2015년 7월 30일
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
Walter Roberson
Walter Roberson 2015년 7월 30일
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);

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by