Input clarification for the fmincon function
显示 更早的评论
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 个评论
Torsten
2022-8-2
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
2022-8-3
Walter Roberson
2022-8-3
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
2022-8-3
Walter Roberson
2022-8-3
yes
Matt J
2022-8-3
'Optimize',false can be abbreviated to 'optim', false if desired
Matt J
2022-8-3
Why use the Symbolic Math Toolbox at all? Your function and its derivatives look very easy.
Davide Mastrodicasa
2022-8-3
回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Solver Outputs and Iterative Display 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!