Run Nested FOR-loop Parallelly for Multivariable Function Optimization
Show older comments
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 Comment
Sam Marshalik
on 17 Dec 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
Accepted Answer
More Answers (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 Comments
Matt J
on 17 Dec 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
on 17 Dec 2021
Edited: Joshua Roy Palathinkal
on 18 Dec 2021
Joshua Roy Palathinkal
on 17 Dec 2021
Edited: Joshua Roy Palathinkal
on 18 Dec 2021
Categories
Find more on Surrogate Optimization in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!