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 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