function [f,g] = rosenbrockwithgrad_s(x)
X = sym('x', [1 2]);
F = 100*(X(2) - X(1)^2)^2 + (1-X(1))^2;
f = double( subs(F, X, x) );
if nargout > 1
G = diff(F);
g = double( subs(G, X, x) );
end
However, this would involve repeated calculation of diff(F) symbolically, which is pointless. Instead you would do something like,
function [f, g] = f_and_g(x, F, G)
f = F(x);
if nargout > 1
g = G(x);
end
end
together with (outside)
X = sym('x', [1 2]);
f = 100*(X(2) - X(1)^2)^2 + (1-X(1))^2;
g = diff(f);
F = matlabFunction(f, 'vars', {X});
G = matlabFunction(g, 'vars', {X});
x = fminunc( @(x) f_and_g(x, F, G), x0 )
Best Answer