How to use the parfor function inside a for loop?

조회 수: 3 (최근 30일)
Yro
Yro 2021년 10월 29일
답변: Raymond Norris 2021년 10월 29일
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