The PARFOR loop cannot run due to the way the variable is used

조회 수: 8 (최근 30일)
Anas Khan
Anas Khan 2022년 10월 29일
편집: Matt J 2022년 10월 29일
I do not believe there is a way to further vectorize this code. Please let me know if that is untrue. I would like to parallelize the below code. The goal of the routine is to take the structure array "data", extract values from the fields "goPower" and "ngPower" for each element in the struct, perform some operation, and store the result in a 2-D matrix of size 1501 x number_of_elements_in_struct. (1501x7) for example. I expect MatLab to distribute iterations of the PARFOR loop (corresponding to permi looping index) to workers and have each worker perform the inside loop separately. Since each "subject" is different and each iteration of permi does something different, I don't think I have any dependencies. MatLab still says "The PARFOR loop cannot run due to the way the variable "diff" is used. What am I doing wrong?
parfor permi = 1:npermutations
for subject = 1:numel(data)
% Get indices for subsampled set of Go trials = to # of No-Go trials
idxs = randsample(size(data(subject).goPower,2),size(data(subject).ngPower,2),true);
% Combine trials
allTrials = cat(3,data(subject).goPower(:,idxs,:),data(subject).ngPower);
% Making mapping vector
mapping = [ones(size(allTrials,3)/2,1); ones(size(allTrials,3)/2,1)+1];
% Shuffle the mapping vector
new_map = mapping(randperm(numel(mapping)));
% Calculate mean difference
diff(:,subject) = mean( mean( allTrials(:,new_map==2,:) ,2) - mean( allTrials(:,new_map==1,:) ,2) ,3);
end
% Store values for this iteration
perm_diffs(permi,:) = mean(diff,2);
end

채택된 답변

Matt J
Matt J 2022년 10월 29일
편집: Matt J 2022년 10월 29일
Pre-allocate temporary variables like diff within the parfor loop.
parfor permi = 1:npermutations
diff=nan(M,N); %pre-allocate diff
for subject = 1:numel(data)

추가 답변 (0개)

카테고리

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

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by