Problem with parfor and matrix indexing

조회 수: 1 (최근 30일)
Guilherme Freches
Guilherme Freches 2019년 9월 18일
답변: Edric Ellis 2019년 9월 19일
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?

답변 (1개)

Edric Ellis
Edric Ellis 2019년 9월 19일
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);

카테고리

Help CenterFile Exchange에서 Parallel for-Loops (parfor)에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by