Setting up properly the fminunc function
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Dear all,
I am trying to maximize this function
T=1000;
z=randn(T,1);
u=randn(T,1);
k1=0.01;
k2=0.01;
options=optimset('LargeScale','off','display','off','TolFun',0.0001,'TolX',0.0001,...
'GradObj','off', 'Hessian','off','DerivativeCheck','off');
for t=1:T
[x,fval,exitflag,output,G_sum,H]=fminunc('funct',u(t),options,...
z,k1, k2,t, u,T);
end
where
function LL= funct(x,z,k1, k2,t, u,T)
if t==1
u=[x; u(2:T) ];
elseif t==T
u=[u(1:T-1);x ];
else
u=[u(1:t-1);x;u(t+1:T) ];
end
e2=(z-u).^2;
kk= - 0.5*x^2/k2;
LL = -( -.5/k1*sum(e2(t:T))+kk) ;
end
However, I am not sure if the function is properly set up in terms of 'x'. As you can see 'x' changes position within 'u'.
I suspect that an alternative approach would be
function LL= funct(x,z,k1, k2,t, u,T)
u(t)=x;
e2=(z-u).^2;
kk= - 0.5*x^2/k2;
LL = -( -.5/k1*sum(e2(t:T))+kk );
end
Which of the two is more efficient? Is there any alternative solution?
Thanks in advance.
3 commentaires
Réponse acceptée
Walter Roberson
le 27 Mai 2019
T=1000;
z=randn(T,1);
u=randn(T,1);
k1=0.01;
k2=0.01;
options = optimset('LargeScale','off','display','off','TolFun',0.0001,'TolX',0.0001,...
'GradObj','off', 'Hessian','off','DerivativeCheck','off');
x = zeros(1, T); fval = zeros(1,T); exitflag = zeros(1,T);
output = cell(1,T); G_sum = cell(1,T); H = cell(1,T);
for t = 1:T
[x(t), fval(t), exitflag(t) ,output{t}, G_sum{t}, H{t}] = fminunc(@(x) funct(x, z, k1, k2, t, u, T), u(t), options);
end
function LL = funct(x, z, k1, k2, t, u, T)
u(t) = x;
e2 = (z-u).^2;
kk = - 0.5*x^2/k2;
LL = -( -.5/k1*sum(e2(t:T))+kk );
end
If you only include e2(t:T) in your sum, then it is not clear to me why you are calculating e2 over the whole vector? Why not, for example,
for t = 1:T
[x(t), fval(t), exitflag(t) ,output{t}, G_sum{t}, H{t}] = fminunc(@(x) funct(x, z, k1, k2, u(t:end)), u(t), options);
end
function LL = funct(x, z, k1, k2, urest)
urest(1) = x;
e2 = (z-urest).^2;
kk = - 0.5*x^2/k2;
LL = -( -.5/k1*sum(e2)+kk );
end
3 commentaires
Walter Roberson
le 28 Mai 2019
The first of those calculates for all t values, throwing away all of the intermediate results and keeping only the last result. It would not leave you with an x for t = 1, an x for t = 2, and so on, only with an x for t = T.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Surface and Mesh Plots dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!