Search code examples
matlabsymbolic-mathhessian-matrix

Write function with dynamic variables to get its Hessian matrix using syms, f, and hessian


My problem has 60 variables (x1 to x60) and here is the function:

f=(x1+x2+x3)*x1+(x2+x3+x4)*x2+...+(x58+x59+x60)*x58

I want to get the Hessian matrix of the function f. However, because there are so many variables, I don't want to write them one by one for syms and f.

I know I can manually calculate the Hessian matrix of the function f as the function is not too difficult. However, I occasionally need to change the form of the function, such as changing the function to (increase the number of variables in the brackets):

f=(x1+x2+x3+x4)*x1+(x2+x3+x4+x5)*x2+...+(x57+x58+x59+x60)*x57

Therefore, I don't want to manually compute the Hessian matrix of function f as long as the function form changes. Is there any easier way to use syms to write f with these 60 variables in MATLAB so that I can use hessian to get the Hessian matrix of f?


Solution

  • First, given the regular and simple nature of the function f described, your Hessian has a defined structure that can be directly calculated numerically. Like this, for example:

    n = 60; % number of variables
    b = 3;  % number of terms in parentheses
    h = diag(2+zeros(n,1));
    for i = 1:b-1
        d = diag(ones(n-i,1),i);
        h = h+d+d.';
    end
    h(n-b+2:n,n-b+2:n) = 0
    

    This can be done without a for loop via something like this:

    n = 60; % number of variables
    b = 3;  % number of terms in parentheses
    h = full(spdiags(repmat(ones(n,1),1,2*b-1),1-b:b-1,n,n)+speye(n));
    h(n-b+2:n,n-b+2:n) = 0
    

    Symbolically, you can create a vector of variables with sym to create your function and calculate the Hessian like this:

    n = 60; % number of variables
    b = 3;  % number of terms in parentheses
    x = sym('x',[n 1]); % vector of variables
    f = 0;
    for i = 1:n-b+1
        f = f+sum(x(i:i+b-1))*x(i);
    end
    h = hessian(f,x)
    

    It's possible to remove the for loops, but there won't be much performance benefit.