Input clarification for the fmincon function
Show older comments
Hello everyone,
I'm trying to use the fmincon funtion but I'm having some problems with the input of the function.
I have a fairly complicated problem and I'm generating the function to be minimized f(v) by using Matlab symbolic variables in order to calculate the Gradient and the Hessian of this function by using the Symbolic Math Toolbox:
function [f,g,gg]=CostFunction(t,Y,Nvar,Epsilon)
% Symbolic Cost function, Gradient and Hessian
sympref('FloatingPointOutput',true);
Hsym=sym(zeros(length(t),1)).';
for i = 1:Nvar
v{i} = sprintf('v%d%d',i);
end
v = v(:);
v = sym(v, 'real');
for i = 1:4:Nvar
Hsym = Hsym+v(i).*exp(-v(i+1).*t).*cos(2.*pi.*v(i+3).*t+v(i+2)); % Impulse Responce Function
end
tic
f_sym = sum((Hsym-Y).^2)-Epsilon; % Cost Function
f=matlabFunction(f_sym);
g_sym = jacobian(f_sym,v).'; % Gradient Function
for i=1:length(g_sym)
g{i}=matlabFunction(g_sym(i));
end
gg_sym = jacobian(g_sym,v); % Hessian Function
for i=1:length(gg_sym)
for j=1:length(gg_sym)
gg{i,j}=matlabFunction(gg_sym(i,j));
end
end
end
What I get from this code is a function f(v) and a cell array cointining the gradint function g(v) and the hessian function gg(v).
How can I provide these functions to the minimization algorithm fmincon? A possible solution is, as suggested in this link, to use something like:
matlabFunction(f,g,gg,'file',filename,'vars',{v});
but it takes a lot of computational time.
You can find attatched the Workspace for running this script.
Is there another way to use f,g,gg inside fmincon?
Thank you in advance for your help.
Best Regards,
Davide
8 Comments
Torsten
on 2 Aug 2022
matlabFunction(f,g,gg,'file',filename,'vars',{v});
but it takes a lot of computational time.
Do it once, save the expressions to file and for further runs, use the function files instead of the symbolic computations.
Davide Mastrodicasa
on 3 Aug 2022
Walter Roberson
on 3 Aug 2022
matlabFunction(f,g,gg,'file',filename,'vars',{v});
I recommend using 'optim', false when you write to file. There are bugs in the optimization process in recent releases. Not optimizing saves a fair bit of time too.
Davide Mastrodicasa
on 3 Aug 2022
Walter Roberson
on 3 Aug 2022
yes
Matt J
on 3 Aug 2022
'Optimize',false can be abbreviated to 'optim', false if desired
Matt J
on 3 Aug 2022
Why use the Symbolic Math Toolbox at all? Your function and its derivatives look very easy.
Davide Mastrodicasa
on 3 Aug 2022
Answers (0)
Categories
Find more on Solver Outputs and Iterative Display 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!