Issue with parallel loop
Ältere Kommentare anzeigen
Can somebody point out to me what is wrong with the following parallel structure, and/or tell me how to fix it. I keep getting a restricted indices error, but I don't see what is wrong with these indices for MX2. ind will always be an integer and it will always be unique across any unique set of f,j,i.
q = 45;
vec = randn(3,q,q,6);
MX2 = zeros(6*(q)^2,2);
parfor f = 1:6
for j = 1:q
for i = 1:q
ind = (f-1)*q^2+(j-1)*q+i;
V = vec(:,i,j,f)-vec(:,i+1,j+1,f);
MX2(ind,1) = norm(V);
V2 = vec(:,i+1,j,f)-vec(:,i,j+1,f);
MX2(ind,2) = norm(V2);
end
end
end
MX2 = MX2.^2;
MX2 = max(MX2(:));
Thanks in advance.
Akzeptierte Antwort
Weitere Antworten (3)
Walter Roberson
am 17 Jun. 2015
V = vec(:,i,j,f)-vec(:,i+1,j+1,f);
V2 = vec(:,i+1,j,f)-vec(:,i,j+1,f);
MX2(ind,:) = [norm(V), norm(V2)];
You were not using "consistent indexing" for MX2: in one place you had ind,1 and in the other place you had ind,2 . So instead you create a vector and assign the vector into the slice.
1 Kommentar
Andrew
am 18 Jun. 2015
You'll need to read Classification of Variables in Parfor Loops. Basically, because MX2 is both defined prior to the parfor loop and assigned values within the loop, parfor has no choice but to classify it as a "sliced variable". But there are all kinds of restrictions on how you can index sliced variables that are discussed at the link. Even though your indexing is parallelizable in theory, there are simply limits on parfor's ability to recognize this. Hence, the restrictions.
In any case, the use of parfor is not appropriate/optimal here. The operations you are performing are abundantly vectorizable,
V = vec(:,1:end-1,1:end-1,:)-vec(:,2:end,2:end,:);
Vnorms = sqrt(sum(reshape(V,3,[]).^2));
V2 = vec(:,2:end,1:end-1,:)-vec(:,1:end-1,2:end,f);
V2norms = sqrt(sum(reshape(V2,3,[]).^2));
MX2=[Vnorms(:),V2norms(:)];
1 Kommentar
Andrew
am 18 Jun. 2015
Here's a parfor-based solution that avoids multiple nested loops, though I still advocate the vectorized approach in my earlier Answer.
q = 45;
vec = randn(3,q+1,q+1,6);
MX2 = zeros(6*(q)^2,2);
parfor ind = 1:6*q^2
[i,j,f]=ind2sub([q,q,6],ind);
V = vec(:,i,j,f)-vec(:,i+1,j+1,f);
V2 = vec(:,i+1,j,f)-vec(:,i,j+1,f);
MX2(ind,:) = [norm(V), norm(V2)];
end
MX2 = MX2.^2;
MX2 = max(MX2(:));
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!