Use of fmincon with nonlcon inside a parfor loop
5 views (last 30 days)
Show older comments
Hello,
I have the following code which is working fine... but slowly
for ii=1:9000
fun = @p expression(p);
wref=0;
zref=1;
loc_nlcon = @p nlcon(p,wref,zref);
output=fmincon(fun,init,[],[],[],[],lb, ub,loc_nlcon);
end
function [c,ceq]=nlcon(p,w,z)
c=0;
ceq=z-expression(p,w);
end
I want to speed it up by using a parfor loop. However, as nlcon is a nested function, for loop cannot simply changed by a parfor one. By using an handle function (see below), my issue is that fcn returns only the first function parameter (c) and not both (c and ceq) as needed by fmincon. I am struggle finding the good solution to my problem.
parfor ii=1:9000
fun = @p expression(p);
fcn = @nlcon;
wref=0;
zref=1;
output=fmincon(fun,init,[],[],[],[],lb, ub,fcn(p,wref,zref));
end
function [c,ceq]=nlcon(p,w,z)
c=0;
ceq=z-expression(p,w);
end
Thank you for your help.
Best
4 Comments
Matt J
on 20 Oct 2023
Edited: Matt J
on 20 Oct 2023
@Guilhem Pages Why does your nlcon function need to be nested? Your posted code isn't using any externally-scoped variables or other unique features of nested functions. Why not just make it a local function?
Accepted Answer
Matt J
on 20 Oct 2023
Edited: Matt J
on 20 Oct 2023
Move the steps inside the loop to its own function doOptimization(). You can nest functions there, as in in the example below.
function main()
N=10;
output=cell(N,1);
parfor i=1:10
output{i}=doOptimization();
end
end
function output=doOptimization
fun = @(p) p.^2;
wref=0;
zref=1;
[init,lb,ub]=deal(2,-1,4);
loc_nlcon = @(p) nlcon(p,wref,zref);
output=fmincon(fun,2,[],[],[],[],lb, ub,loc_nlcon);
function [c,ceq]=nlcon(p,w,z) %nested
c=0;
ceq=z-(p.^2+w);
end
end
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!