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);

カテゴリ

Find more on Problem-Based Optimization Setup in Help Center and File Exchange

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by