Monte Carlo Simulation with Parfor
3 次查看(过去 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?
0 个评论
回答(1 个)
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
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 Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!