Question

I am having an issue with manipulating the function handles of my gradient and hessian.

I have the following code:

syms x1 x2

x = [x1,x2];

% Define the function phi(x)
phi = @(x1,x2) 10*x1^4 - 20*x1^2*x2 + 10*x2^2 + x1^2 - 2*x1 + 5; 

% Define the gradient of the function phi(x)
gradphi = @(x1,x2) jacobian(phi,x).';

% Define the Hessian of phi(x)    
hessphi = @(x1,x2) jacobian(gradphi,x);

Now when I input into the command terminal:

phi(1,2)

I get some scalar value.

But when I input

gradphi(1,2)
hessianphi(1,2)

I want the corresponding vector for the gradient evaluated at those points.

For the gradient, I just get

EDU>> gradphi(1,2)

ans =

2*x1 - 40*x1*x2 + 40*x1^3 - 2
            - 20*x1^2 + 20*x2

Which is just the grad vector function. But I want the actual numerical result inputting x1 = 1 and x2 = 2.

EDU>> hessphi(1,2)

returns an error.

I am not sure why.

Was it helpful?

Solution

For multiplications and divisions on arrays, you need to use element-wise operators .*, ./, and .^ in the definition of hessianphi and gradphi. Otherwise, Matlab will try do do matrix multiplication/division/power, which won't go well.

/aside: searching for the text of the error message will bring up the most likely causes of the error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top