calculate a n dimensional jacobian matrix without the symbolic toolbox so without using jacobian in matlab

To calculate a n-dimensional Jacobian matrix without using the symbolic toolbox in MATLAB, we can use numerical differentiation techniques. Numerical differentiation is a method of approximating the derivative of a function at a point by computing the values of the function at nearby points.

Suppose we have a vector-valued function f: R^n -> R^m, which maps a vector x in R^n to a vector f(x) in R^m. The Jacobian J of f is an m by n matrix which contains the partial derivatives of the function f with respect to its n variables. Specifically, the (i,j) entry of J is given by the partial derivative of the i-th component of f with respect to the j-th variable of x.

To compute the Jacobian matrix numerically, we can use the finite difference method. For each variable j, we can estimate its partial derivative by computing the finite difference:

(f(x + h*e_j) - f(x))/h

where e_j is the j-th basis vector and h is a small positive number. This formula gives us an approximation of the partial derivative of f with respect to the j-th variable at x.

We can compute the entire Jacobian matrix J by applying this formula for each variable j = 1, ..., n. We can do this efficiently using MATLAB's vectorization capabilities:

main.m
function J = jacobian(f, x)
    m = numel(f(x));  % number of function outputs (rows of J)
    n = numel(x);     % number of function inputs (columns of J)
    J = zeros(m, n);   % pre-allocate Jacobian matrix
    
    h = 1e-6;  % size of finite difference
    
    % compute each column of the Jacobian matrix
    for j = 1:n
        e_j = zeros(n, 1);
        e_j(j) = 1;  % j-th basis vector
        
        % compute the j-th column of the Jacobian
        J(:,j) = (f(x + h*e_j) - f(x))/h;
    end
end
509 chars
17 lines

This function takes as input a function handle f and a vector x, and returns the Jacobian matrix J of f at x. The function assumes that f returns a vector of the same length for any input x. The size of the finite difference h can be adjusted to balance accuracy and computational efficiency.

Note that this approach is subject to numerical errors, especially when h is very small, so care must be taken in choosing an appropriate value for h. In addition, this method may not work well for functions that are highly nonlinear or have discontinuities. In these cases, more advanced numerical differentiation techniques may be needed.

gistlibby LogSnag