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

parallel computingParallel Computing Toolboxparfor

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

Best Answer

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