How to use the parfor function inside a for loop?

3 次查看(过去 30 天)
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

回答(1 个)

Raymond Norris
Raymond Norris 2021-10-29
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);

类别

Help CenterFile Exchange 中查找有关 Parallel Computing Toolbox 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by