1
votes

The following code calculates the matrix elements of A from the vector v. I try to use parfor to speedup the calculation as the dimension of v is very large. I get an error of "The variable A in a parfor cannot be classified.". Any suggestions on how to solve the problem?

A = zeros(n,n);
for kk = 1:D
    % sk = <expressions...>
    % ek = <expressions...>
    parfor ll = 1:D
        % sl = <expressions...>
        % el = <expressions...>
        if (ek == el)
            A(sk,sl) = A(sk,sl) + v(kk) * v(ll);
        end
    end
end
2

2 Answers

0
votes

The problem is that you distribute A over different cores but adjust its value by itself. How should a core know that the entry A(sk,sl) wasn't changed on a different core? It needs to check this, communicating with all other cores, eliminating any parallel computation, which is why MATLAB complains about it: MATLAB complaint

You can avoid the problem by creating a copy of A outside the parfor-loop

A = zeros(n,n);
B = A;
for kk = 1:D
    % sk = <expressions...>
    % ek = <expressions...>
    parfor ll = 1:D
        % sl = <expressions...>
        % el = <expressions...>
        if (ek == el)
            B(sk,sl) = A(sk,sl) + v(kk) * v(ll);
        end
    end
end
0
votes

You could formulate this as a "reduction" over A like this:

parfor ll 1:D
    % compute stuff...

    % Make a new matrix for the increment
    Aincrement = zeros(n, n);
    % Fill out the element of the increment
    Aincrement(sk, sl) = v(kk) * v(ll);
    % Increment the whole of A so that parfor can 
    % treat A as a reduction variable
    A = A + Aincrement;
end

This might well be inefficient if n is large.