symJac

Return a symbolically generated gradient / Jacobian from a function handle

Syntax

jac = symJac(fun)

jac = symJac(fun,nvar)

jac = symJac(fun,nvar,tran)

jac = symJac(fun,ncol,tran,var)

jac = symJac(fun,ncol,tran,var,file)

[jac,pattern] = symJac(fun)

[jac,pattern,symjac] = symJac(fun)

Description

jac = symJac(fun) converts the function handle fun into a symbolic expression, differentiates it using the Symbolic Toolbox command Jacobian, then converts it back to a function handle as jac.

jac = symJac(fun,nvar) ensures the correct number (nvar) of variables is used in the resulting gradient / Jacobian. This is useful if your function does not include all indices of x.

jac = symJac(fun,nvar,tran) returns the function transposed.

jac = symJac(fun,nvar,tran,var) allows a variable other than 'x' to be parsed from the expression.

jac = symJac(fun,nvar,tran,var,file) writes the symbolic Jacobian to a file, rather than returning it as an anonymous function. Only supports .m files currently.

[jac,pattern] = symJac(fun) returns the Jacobian sparsity pattern as a function handle.

[jac,pattern,symjac] = symJac(fun) also returns the intermediate symbolic expression of the gradient / Jacobian.

Important Notes

This function uses the Matlab Symbolic Toolbox® thus you must have this installed to use this function. This is also a very basic routine thus you may wish to confirm the solution via one of the other differentiation routines provided.

The form of your function handle must be as follows:

fun = @(x) x(1) + x(2);  where the function is only a function of x, and x is indexed into the expression (no vectorized calls).

Example

>> fun = @(x) 3*x(1)^2 + 4*sin(x(2));

>> jac = symJac(fun)

jac =

@(x)[[6*x(1),4*cos(x(2))]]