MATLAB: Sliced variable index problem for parfor

parforsliced variable

Hi, I'm trying to select some Items from a 4D matrix using a parfor, but I get the sliced variables error, can't figure what is wrong. The indexing is clearly independent for each loop, all values in Idx_ValidGM are different.
for ii=1:size(NumStories,1)
X_index = (ii-1)*size(T_Obj,2)*size(Q,1)*(NumGM - size(Discard,1));
for jj=1:size(T_Obj,2)
X_index = X_index + (jj-1)*size(Q,1)*(NumGM - size(Discard,1));
for kk=1:size(Q,1)
X_index = X_index + (kk-1)*(NumGM - size(Discard,1));
parfor ll = 1:NumGM
if Idx_ValidGM(ll) > 0
Index = X_index + Idx_ValidGM(ll);
Y_in(Index) = MaxMuMat(ii,jj,kk,ll);
end
end
end
end
end

Best Answer

all values in Idx_ValidGM are different
PARFOR has no way of knowing that. In any case, there is a far easier solution not involving parfor:
Lidx=Idx_ValidGM(ll) > 0;
IdxValid=Idx_ValidGM(Lidx);
data=MaxMuMat(:,:,:,Lidx);
for ii=1:size(NumStories,1)
X_index = (ii-1)*size(T_Obj,2)*size(Q,1)*(NumGM - size(Discard,1));
for jj=1:size(T_Obj,2)
X_index = X_index + (jj-1)*size(Q,1)*(NumGM - size(Discard,1));
for kk=1:size(Q,1)
X_index = X_index + (kk-1)*(NumGM - size(Discard,1));
Index=X_index + IdxValid;
Y_in(Index)=data(ii,jj,kk);
end
end
end