1
votes

In my for loop, I set a matrix variable ga to save the results of every loop. But when I change the for loop to the parfor loop (to accelerate), there is a warning as follows:

enter image description here

And when I run the code, I get another error:

enter image description here

The code is:

R=100;
alpha_set = [1,2,3,4,5]; % This is an index set
ga = zeros(2,5); % to save results of addition

parfor h=1:R

[A1,A2] = random_sample(A,0.6);

...

for ai=1:5
    alpha = alpha_set(ai);
    ga(1,ai) = ga(1,ai) + T_lower(A2,alpha)/R;
    ga(2,ai) = ga(2,ai) + T_upper(A2,alpha)/R; % accumulation
end

end

T_upper and T_lower are both functions which return numbers.

I want to sum the returns of the two functions, and save the values under different index alpha to different positions of ga, so ga should be classified as reduced variable, shouldn't it? (While Matlab cannot classify it.)

How can I debug the code and make parfor run successfully?

1

1 Answers

1
votes

You define the array to hold the result before the parfor loop, but then try and access it from within the parallel loop. As noted, Matlab cannot classify the variable. The problem is that ga is indexed inside the nested for-loop. The code below uses a variable that is indexed differently to address this issue.

R=100;
alpha_set = [1,2,3,4,5]; % This is an index set 
N = 2;
gas = zeros(R,length(alpha_set),N);



parfor h=1:R

    A = 1.0;
    [A1,A2] = random_sample(A,0.6);


    for ai=1:5
        alpha = alpha_set(ai);
        for ni = 1:N
            switch ni
                case 1
                    gas(h,ai,ni) = T_lower(A2,alpha)/R;
                case 2
                    gas(h,ai,ni) = T_upper(A2,alpha)/R;
             end
        end
    end


end

gaResults = zeros(N,length(alpha_set));

for ni = 1:N 
    gaResults(ni,:) = sum(gas(:,:,ni),1);
end

function [ output ] = T_lower( a1,a2 )
output = a1*a2;
end

function [ output ] = T_upper( a1,a2 )
output = a1+a2;
end

function [o1,o2] = random_sample(a1,a2) 
output = a1 + a2.*randn(1,2);
o1 = output(1);
o2 = output(2);
end