how do i run this parallel programming using parfor?

1 view (last 30 days)
i'm trying to run insertion sort as a parallel programming using parfor, but it gives me some kind of error which I cant fix, here is the code:-
clear A
t=cputime;
x = 1 : 100;
n = length(x);
parfor j = 2:n
pivot = x(j);
i = j;
while ((i > 1) && (x(i - 1) > pivot))
x(i) = x(i - 1);
i = i - 1;
end
x(i) = pivot;
end
cputime-t
Error: The variable x in a parfor cannot be classified.
See Parallel for Loops in MATLAB, "Overview".

Accepted Answer

Walter Roberson
Walter Roberson on 12 Nov 2015
It is not allowed to access the distributed variable at two different indices.
The code you are doing that moves the pivot earlier and earlier would have different results depending upon the iterations for the earlier j had already been run or not. That is not allowed: every parfor iteration needs to be independent of the other iterations so that the order the iterations are run in does not matter (except for accumulated round-off error in "reduction variables".)
  3 Comments
Walter Roberson
Walter Roberson on 13 Nov 2015
I don't think I would try to run an insertion sort as a parallel routine.
If I did, I would work it on the idea of breaking up into blocks each done in parallel. Any sufficiently small block would be sorted "locally" (it is too expensive to go parallel below a good size.) Once you have blocks that are each partially sorted, you can start merging them, taking advantage of the partial ordering by keeping track of the maximum and minimum in the block to know whether a given value sorts before, after, or within the block. But getting this to work right would probably approach closely to just doing a quicksort.

Sign in to comment.

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!