How can I get parfor to work when a cycle is parallelizable but I cannot slice a variable in disjoint chunks?

1 回表示 (過去 30 日間)
I am very new to the Parallel Computing Toolbox and I am trying to parallelize a simple "for" cycle. In short, I have an array A of length, say, n+2, and my cycle looks like this:
M = zeros(n,1);
parfor i = 1:n
M(i) = feval(f,A(i:i+2));
end
where f is a function handle. That is, each iteration needs three adjacent entries of the array. Since A is a read-only variable, results are independent from the order in which the iterations are executed, so I guessed I could get Matlab to perform the cycle in parallel.
Problem is, A is not a sliced variable and I can't think of a way to make it such, so the Matlab editor complains as soon as I try to use parfor. Can anyone suggest me a solution or a workaround?
Thanks

採用された回答

Jill Reese
Jill Reese 2013 年 2 月 14 日
Try aliasing your A variable like so:
A0 = A;
A1 = A;
A2 = A;
Then inside the parfor loop, when you need A(i) use A0(i) instead. Here's an example of how the tranformation might work given your code above:
A = rand(n+2,1);
A0 = A;
A1 = A;
A2 = A;
M = zeros(n,1);
parfor i = 1:n
tempA = [A0(i), A1(i+1), A2(i+2)];
M(i) = feval(f, tempA);
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by