Compute the Jacobian of the function.
J = diffcode_jacobian(f,x)
a function or a list, the function to differenciate.
a n-by-1 matrix of doubles, real, the point where to compute the derivatives
a n-ny-m matrix of doubles, the exact Jacobian. The column J(:,k)
approximates the gradient of fk
, for k=1,2,...,m
.
Computes the exact Jacobian matrix of the function. The algorithm uses an exact differentiation method.
If f
is a compiled function, then diffcode_jacobian
cannot differentiate f
.
The function must have header
y = f( x )
where
x is a n-by-1 matrix of doubles,
y is a m-by-1 matrix of doubles.
It might happen that the function requires additionnal
arguments to be evaluated.
In this case, we can use the following feature.
The function f
can also be the list (func,a1,a2,...)
where, func
, the first element in the list,
must be a function with header
y = func ( x , a1 , a2 , ... ).
In this case, the input arguments a1, a2, ...
will be automatically be appended at the
end of the calling sequence of func
.
The diffcode_jacobian
function calls the function
f
several times in order to compute its
derivatives.
The total function evaluations is n
times, where n
is the size of x
.
// The function to differentiate function y=f(x) f1 = sin(x(1)*x(2))+exp(x(2)*x(3)+x(1)) f2 = sum(x.^3) y=[f1;f2] endfunction // The exact gradient function J=exactg(x) g1(1) = cos(x(1)*x(2))*x(2)+exp(x(2)*x(3)+x(1)) g1(2) = cos(x(1)*x(2))*x(1)+exp(x(2)*x(3)+x(1))*x(3) g1(3) = exp(x(2)*x(3)+x(1))*x(2) // g2(1) = 3*x(1)^2 g2(2) = 3*x(2)^2 g2(3) = 3*x(3)^2 // J(:,1)=g1 J(:,2)=g2 endfunction // Compute the exact Jacobian x=[1;2;3]; J = diffcode_jacobian(f,x) Jexact = exactg(x) and(J==Jexact) // Passing extra parameters function y=G(x, p) f1 = sin(x(1)*x(2)*p)+exp(x(2)*x(3)+x(1)) f2 = sum(x.^3) y=[f1; f2] endfunction p=1; h=1e-3; J=diffcode_jacobian(list(G,p),x) | ![]() | ![]() |