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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by