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 Center および File ExchangeParallel for-Loops (parfor) についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by