1

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?

horchler
  • 18,384
  • 4
  • 37
  • 73
Naomi Li
  • 25
  • 4

1 Answers1

0

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.

horchler
  • 18,384
  • 4
  • 37
  • 73
  • Thank you Horchler very much for providing different options to address my question! The codes are what I need. BTW, thank you for the grammar editing :-) – Naomi Li Feb 16 '18 at 20:42
  • Hi Horchler, I met an error when using the symbolical way. It was okay to construct the symbolic variables and the function f. However, when implement h=hessian(f,x), there is always an error: "Error using sym/subsindex (line 737) Invalid indexing or function definition. When defining a function, ensure that the arguments are symbolic variables and the body of the function is a SYM expression. When indexing, the input must be numeric, logical, or ':'." Do you know why? – Naomi Li Feb 22 '18 at 23:35
  • @NaomiLi: What `version` of MATLAB are you using? Are you using exactly the code above in my answer? – horchler Feb 23 '18 at 03:03
  • Yep, I am using Matlab R2015b. I don't know why but the error always come; however, when I tried to use jacobian(gradient(f,x),x), it works without error. – Naomi Li Feb 26 '18 at 16:54