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

1 view (last 30 days)
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

Accepted Answer

Jill Reese
Jill Reese on 14 Feb 2013
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

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!