1

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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

However, when I have to use a matrix to store the results of different functions with a similar index, this method is tedious. For example, if I have a family of functions, such as T_1,T_2, ...,T_n, then I have to define ga1, ga2, ..., ga_n. It'll be a frustrating repetition. How to avoid this problem?
Perhaps you could increase the dimensions of the results array? For example see the edited answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.