Problem with parfor and matrix indexing

4 vues (au cours des 30 derniers jours)
Guilherme Freches
Guilherme Freches le 18 Sep 2019
Hey
I'm building a knn graph out of an adjacency matrix M and it seems to take some time when the number of columns is large enough.
I'm trying to paralelize the process by replacing the for on the following code snippet by a parfor
indi = zeros(1, neighbours * n);
indj = zeros(1, neighbours * n);
inds = zeros(1, neighbours * n);
parfor ii = 1:n
% Compute i-th column of distance matrix
dist = euclidean(repmat(M(:, ii), 1, n), M); %gives a euclidean distance matrix
% Sort row by distance
[s, O] = sort(dist, 'ascend');
% Save indices and value of the neighbours
indi(1, (ii-1)*neighbours+1:ii*neighbours) = ii;
indj(1, (ii-1)*neighbours+1:ii*neighbours) = O(1:neighbours);
inds(1, (ii-1)*neighbours+1:ii*neighbours) = s(1:neighbours);
end
But I keep running into the error : Valid indexes of indi, indj and inds are restricted by parfor.
Any idea what to do here?

Réponses (1)

Edric Ellis
Edric Ellis le 19 Sep 2019
In each case, you're attempting to assign neighbours elements into each of your output arrays. The restrictions on parfor sliced output variables are that must use the loop index as one subscript, and use a fixed index listing in the other positions. See the doc: https://uk.mathworks.com/help/parallel-computing/sliced-variable.html . The simplest way to fix this case is to make each of your output arrays a 2-D matrix, and assign whole rows at a time, like this:
indi = zeros(n, neighbours);
parfor ii = 1:n
indi(ii, :) = ii;
end
If you need to, you can reshape the result back later
indi = reshape(indi, 1, n * neighbours);

Catégories

En savoir plus sur Parallel for-Loops (parfor) dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by