Run Nested FOR-loop Parallelly for Multivariable Function Optimization
Afficher commentaires plus anciens
F_max = 0; % Temp var for max of F
F_curr = 0; % Temp var for current F
for x = -0.02:0.001:0.02
for x_1 = 20:100
for x_2 = 20:100
for x_3 = 20:100
for x_4 = 20:100
for x_5 = -15:15
for x_6 = -15:15
for x_7 = -15:15
for x_8 = -15:15
F_curr = double(F(x,x_1,x_2,x_3,x_4,x_5,x_6,x_7,x_8));
if F_curr>F_max
F_max = F_curr;
end
end
end
end
end
end
end
end
end
end
F is a (symbolic) function of 9 (symbolic) variables x, x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8. The formula of F is given in the following Link1.
How do I edit this code so that it can run parallelly? The reason I can't apply the usual solution is because the variables aren't looping by integer iterations starting from 0 (e.g. i = 1:n (some integer)).
1 commentaire
Sam Marshalik
le 17 Déc 2021
Hey Joshua, I do not currently have an opportunity to play around with the code, but you will want to employ parfor to speed this up. The issue is that F_max is a temporary variable on all of the workers and they will not be able to exchange information to determine who has the highest F_max (parfor workers are not able to communicate with one another).
I think something you can try is making F_max a sliced output variable (https://www.mathworks.com/help/parallel-computing/sliced-variable.html#bq_tiga) - this will give you a large array with all of the values from your loops. You can then determine the highest value (max(F_max)) from the entire list.
You can also do the following to deal with the outermost parfor-loop, since the non-integers will be an issue:
x = 0:0.1:1;
parfor idx = 1:length(x)
disp(x(idx))
end
Réponse acceptée
Plus de réponses (1)
Xgrid ={ -0.02:0.001:0.02;
20:100;
20:100;
20:100;
20:100;
-15:15;
-15:15;
-15:15;
-15:15};
sz=cellfun(@numel,Xgrid);
N=prod(sz);
J=numel(sz);
Fdouble=matlabFunction(F);
F_max=-inf;
parfor n=1:N
sub=cell(J,1);
[sub{1:J}]=ind2sub(sz,n); %convert to subscripts
X=cellfun(@(A,B) A(B), Xgrid,sub,'uni',0); %lookup grid values
F_max=max(F_max, Fdouble(X{:}) ); %reduction
end
3 commentaires
Matt J
le 17 Déc 2021
The formula shown at your link has a number of recurring intermediate quantities. It would therefore improve performance if you used matlabFuntion's code optimization options, like in this example.
This would mean converting F to an mfile instead of to an anonymous function.
Joshua Roy Palathinkal
le 17 Déc 2021
Modifié(e) : Joshua Roy Palathinkal
le 18 Déc 2021
Joshua Roy Palathinkal
le 17 Déc 2021
Modifié(e) : Joshua Roy Palathinkal
le 18 Déc 2021
Catégories
En savoir plus sur Surrogate Optimization dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
