How to implement a parfor in place of a for loop?

1 vue (au cours des 30 derniers jours)
Christopher
Christopher le 11 Juin 2015
Modifié(e) : Christopher le 11 Juin 2015
I understand the idea behind what is and isn't allowed in a parfor loop, but I do not understand the practical application. I have the following segment of code. It works great, but it only uses 1 core and takes hours to complete. It should be trivial to parallelize but I don't see how to do it.
By the way, the preallocations are merely for the purpose of presenting it to you in a way that it will work.
numfiles = 3249;
LABTnum = 61;
for i=1:LABTnum
adjusted_La{i} = rand(10,numfiles);
adjusted_Sm{i} = rand(10,numfiles);
adjusted_Yb{i} = rand(10,numfiles);
end
chem_LaSm = repmat(rand(10,1),1,numfiles);
pcoefs = repmat([0.2 1.0 3.0],numfiles,1)';
h = 2;
Mi = repmat(pcoefs(:,1),1,h+1);
polys = zeros(h+1,numfiles);
M = bsxfun(@power,Mi,0:h);
for i=1:LABTnum
bestCm_LaSm{i} = zeros(numfiles,numfiles);
curSm_LaSm = adjusted_Sm{i}; % for La/Sm
for k=1:numfiles
curLa = repmat(adjusted_La{i}(:,k),1,numfiles);
LaSm = curLa./curSm_LaSm;
difs = [mean((LaSm*0.2-chem_LaSm).^2)' mean((LaSm-chem_LaSm).^2)' mean((LaSm*3-chem_LaSm).^2)']';
for j=1:numfiles;
polys(:,j) = M\difs(:,j);
end
bestCm_LaSm{i}(:,k) = -0.5*polys(2,:)./polys(3,:);
end
end
I do not understand how to modify a code like this in a way that is acceptable for parfor. Any help is appreciated.
EDIT:
I've found that I may rewrite the active part of the code as:
for i=1:LABTnum
bestCm_LaSm{i} = zeros(numfiles,numfiles);
curSm_LaSm = adjusted_Sm{i}; % for La/Sm
parfor k=1:numfiles
polys{k} = zeros(h+1,numfiles);
curLa = repmat(adjusted_La{i}(:,k),1,numfiles);
LaSm = curLa./curSm_LaSm;
difs = [mean((LaSm*0.2-chem_LaSm).^2)' mean((LaSm-chem_LaSm).^2)' mean((LaSm*3-chem_LaSm).^2)']';
for j=1:numfiles;
polys{k}(:,j) = M\difs(:,j);
end
end
for k=1:numfiles
bestCm_LaSm{i}(:,k) = -0.5*polys{k}(2,:)./polys{k}(3,:);
end
end
Is there a better way?

Réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by