Effacer les filtres
Effacer les filtres

How to use the parfor function inside a for loop?

1 vue (au cours des 30 derniers jours)
Yro
Yro le 29 Oct 2021
Hi, I am trying to use the parfor function for parallel calculation inside a for loop. I have a problem to define the variables inside and outside the loop. The following code is a simulated annealing algorithm for optimization. The main problem is for the variables inside the parfor loop for parallel computation, specifically the newsol variable. How can I define this variable correctly?
Thanks in advance.
%% SA Main Loop
for it = 1:iters
pf_sol = sol;
pf_position = sol.Position;
pf_cost = sol.Cost;
pf_BestCost = BestCost;
parfor subit = 1:subiters
pf_sol = sol;
% Create new solution
newsol.Position = Neighbor(pf_position);
newsol.Cost = ObjectiveFunction(newsol.Position);
DELTA = -(newsol.Cost-pf_cost);
if DELTA <= 0
pf_sol = newsol;
else
P = exp(-DELTA/T);
if rand <= P
pf_sol = newsol;
end
end
% Update Best Solution
if pf_sol.Cost >= pf_BestSol.Cost
Pf_BestSol = pf_sol;
end
end
% Store Best
BestCost(it) = BestSol.Cost;
% Display
disp(['Iteration ' num2str(it) ': Best = ' num2str(BestCost(it))]);
% Update temperature
T = T*alpha;
end

Réponses (1)

Raymond Norris
Raymond Norris le 29 Oct 2021
There's a bit of missing code here and some of it doesn't make quite sense, so I might be off on my solution. And, I'm going to assume that newsol is a structure and not an object. If so, trying making the following changes.
From
newsol.Position = Neighbor(pf_position);
newsol.Cost = ObjectiveFunction(newsol.Position);
To
position = Neighbor(pf_position);
cost = ObjectiveFunction(position);
newsol = struct('Position',position,'Cost',cost);

Catégories

En savoir plus sur Parallel for-Loops (parfor) dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by