Matlab Parallelism toolbox : stacking loops in parfor
I'm trying to use the parfor loop in the matlab parallelism package. I'm having a similar problem to this guy : MATLAB parfor slicing issue? . The output matrix doesn't seem to be recognized as a sliced variable. In my specific case, I'm trying to stack use other for loops inside the parfor, and I have trouble applying the solution proposed in the other thread 开发者_开发问答to my problem. Here is a dummy example of what I'm trying to do :
n=175;
matlabpool;
Matred=zeros(n,n);
Matx2Cell = cell(n);
parfor i=1:n
for j=1:n
for k=1:n
Matred(j,k)=exp((j+i+k)/500)
end;
end;
Matx2Cell{i}=Matred;
end;
matlabpool close;
P.S. I know it would work to put the parfor on the k-loop instead of the i-loop... But I'd still like to put it on the i-loop (I believe it would be more time-efficient in my real program).
Thanks a lot Frédéric Godin
You can put Matred = zeros(n);
into the parfor body, but this is very slow. Instead define a function with Matred = zeros(n);
in it: effectively the same thing, but much faster:
function Matred = calcMatred(i,n)
Matred=zeros(n);
for j=1:n
for k=1:n
Matred(j,k)=exp((j+i+k)/500);
end
end
Here is a time comparison:
matlabpool
n = 175;
Matx2Cell = cell(n,1);
tic
parfor i=1:n
Matred=zeros(n);
for j=1:n
for k=1:n
Matred(j,k)=exp((j+i+k)/500);
end
end
Matx2Cell{i}=Matred;
end
toc
tic
parfor i=1:n
Matx2Cell{i}=calcMatred(i,n);
end
toc
matlabpool close
On my machine, it takes 7 seconds for the first one and 0.3 seconds for the second.
Also note that I've changed the declaration of Matx2Cell
to cell(n,1)
since cell(n)
makes an n x n
cell array.
You need to move Matred into the parfor loop body. This needs to be done because each iteration of the parfor needs a new copy of Matred.
n=175;
matlabpool;
Matx2Cell = cell(n);
parfor i=1:n
Matred=zeros(n,n);
for j=1:n
for k=1:n
Matred(j,k)=exp((j+i+k)/500)
end;
end;
Matx2Cell{i}=Matred;
end;
matlabpool close;
精彩评论