Using fminunc with gradient computation

7 visualizaciones (últimos 30 días)
Quentin Pradelle
Quentin Pradelle el 9 de Nov. de 2018
Comentada: Torsten el 9 de Nov. de 2018
Hi, I managed to find the minimizer of a function (see picture), and am now trying to include the computation of the gradient. I can't manage to do it, since the method I use to find the gradient returns an error :
Also I'm wondering why it is useful to compute the gradient in this problem?
<<
<<
>>
>>
% definition of x and y
x=-10:0.1:10;
y=-0.4:0.1:10;
% define a grid (x,y)
[xx,yy]=meshgrid(x,y);
% Evaluation of f(x,y) on this grid
zz = f(xx,yy);
% Quasi Newton
fun = @(x)(x(2) - cos(2*x(1)) - ((x(1).^2)/10)).^2 + exp((x(1).^2 + x(2).^2)/100);
% @ = anonymous function to be used as an argument, x(1) = x, x(2) = y
x0 = [1, 1];
options = optimset('Display','iter', 'GradObj', 'on');
[qN_x, qN_fval] = fminunc(fun, x0, options);
function z = f(x,y)
z = (y - cos(2*x) - ((x.^2)/10)).^2 + exp((x.^2 + y.^2)/100);
end
end

Respuestas (1)

Alan Weiss
Alan Weiss el 9 de Nov. de 2018
To include a gradient in the objective function, have the objective return another output, as explained in the documentation.
You seem to have two definitions of your objective function in your script. The first one ( fun = @(x)…) looks good, in that you have just one variable x. Your second, function z = f(x,y)…, is not correct in that it takes two variables. See the link above for how to write scalar objective functions.
When you are done with your objective function it should look like this;
function [z,gz] = myfun(t)
x = t(1);
y = t(2);
z = (y - cos(2*x) - ((x.^2)/10)).^2 + exp((x.^2 + y.^2)/100);
if nargout > 1 % If a gradient is called for
gz(1) = 2*(y - cos(2*x) - ((x.^2)/10)).^2*(2*sin(2*x) - x/5)...
+ x/50*exp((x.^2 + y.^2)/100);
gz(2) = 2*(y - cos(2*x) - ((x.^2)/10)) + y/50*exp((x.^2 + y.^2)/100);
end
I hope that I didn't ruin your homework problem by giving you too explicit an answer.
Alan Weiss
MATLAB mathematical toolbox documentation
  1 comentario
Torsten
Torsten el 9 de Nov. de 2018
gz(1) = 2*(y - cos(2*x) - ((x.^2)/10)).*(2*sin(2*x) - x/5)...
+ x/50.*exp((x.^2 + y.^2)/100);

Iniciar sesión para comentar.

Categorías

Más información sobre Spline Postprocessing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by