I'm looking at the page for the function fminunc, and they supply the following example of miniminization with an additional supplied gradient:
function [f,g] = rosenbrockwithgrad(x)% Calculate objective f
f = 100*(x(2) - x(1)^2)^2 + (1-x(1))^2;if nargout > 1 % gradient required
g = [-400*(x(2)-x(1)^2)*x(1)-2*(1-x(1)); 200*(x(2)-x(1)^2)];end
For a simple function like this, the gradient can easily be calculated explicitely. However, I am trying to minimize a very similar function, but with a much more complicated gradient. The gradient can be calculated symbolically with the diff function, but is very lengthy, and I would like to be able to easily change the function f without having to modify all the gradients as well. How can I use diff to calculate the gradient symbolically for use in the fminunc function?
Best Answer