Converting this nested for loop for parfor use

조회 수: 4 (최근 30일)
Justin
Justin 2013년 11월 10일
편집: Matt J 2013년 11월 10일
I received some really useful help on a similar problem last night here: http://www.mathworks.com/matlabcentral/answers/105436-converting-this-3-nested-for-loop-for-parfor
But this problem is slightly different. I have three local matrices A,B,C that essentially get inserted in the global matrix Aglobal in three separate places. The local matrices themselves will never be split up if you look closely at the code. For example, all three rows and columns of A will always get inserted together in a 3x3 block, but not in the same places as B or C.
NLoc = 3;
nElem = 100;
nEdge = 300;
Aglobal = zeros(NLoc*nElem);
for k=1:nEdge
index1 = function1(k,...);
index2 = function2(k,...);
% A,B, and C are local matrices of dimension 3x3
[A,B,C] = local_mat(k);
for i=1:NLoc
ie = i+(index1-1)*NLoc;
for j=1:NLoc
je = j+(index1-1)*NLoc;
Aglobal(ie,je) = Aglobal(ie,je) + A(i,j);
end
end
for i=1:NLoc
ie = i+(index2-1)*NLoc;
for j=1:NLoc
je = j+(index2-1)*NLoc;
Aglobal(ie,je) = Aglobal(ie,je) + B(i,j);
end
end
for i=1:NLoc
ie = i+(index1-1)*NLoc;
for j=1:NLoc
je = j+(index2-1)*NLoc;
Aglobal(ie,je) = Aglobal(ie,je) + C(i,j);
end
end
end
  댓글 수: 2
Matt J
Matt J 2013년 11월 10일
Are you sure the 2nd inner for loop (the one that uses B(i,j) is right? It shouldn't involve both index1 and index2, similar to the 3rd loop, e.g.,
for i=1:NLoc
ie = i+(index2-1)*NLoc;
for j=1:NLoc
je = j+(index1-1)*NLoc;
Aglobal(ie,je) = Aglobal(ie,je) + B(i,j);
end
end
Justin
Justin 2013년 11월 10일
Yes, I'm sure that it's correct

댓글을 달려면 로그인하십시오.

답변 (1개)

Matt J
Matt J 2013년 11월 10일
편집: Matt J 2013년 11월 10일
This uses mat2tiles ( Available Here )
index1=zeros(nEdge1,1);
index2=zeros(nEdge1,1);
A=cell(1,nEdge); B=A;C=A;
csize=[NLoc,NLoc];
Aglobal = mat2tiles(zeros(NLoc*nElem),csize);
parfor k=1:nEdge
index1(k) = function1(k,...);
index2(k)= function2(k,...);
[A{k},B{k},C{k}] = local_mat(k);
end
Aidx=sub2ind(csize,index1,index1);
Bidx=sub2ind(csize,index2,index2);
Cidx=sub2ind(csize,index1,index2);
Aglobal(Aidx)=A;
Aglobal(Bidx)=B;
Aglobal(Cidx)=C;
Aglobal=cell2mat(Aglobal);

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by