Matlab: function gradient and Hessian in the same function

234 Views Asked by At

Implement a Matlab function for computation of $ f(x),\nabla f(x),\nabla^2 f(x) $ The function must have the interface: function [f,df,d2f] = FunEx1(x) where $f(x)=f=x^2-2x+3xy+4y^3;$

I tried:

function [f,df,d2f] = FunEx1(x)

f=X.^2-2.*X+3.*X.*Y+4.*Y.^3;

df=[2.*X+3.*Y-2;3*X+12*Y.^2];

d2f=[2,3;3,24.*Y];

end

But I guess something is missing, any help? Or any tutorial ?

ps: which is the proper way to type a code in a question?

1

There are 1 best solutions below

3
On

The input variables must be specified:


function [f,df,d2f] = FunEx1(x)

X = x(1); 
Y = x(2);

f=X.^2-2.*X+3.*X.*Y+4.*Y.^3;

df=[2.*X+3.*Y-2;3*X+12*Y.^2];

d2f=[2,3;3,24.*Y];

end

To call the function write

[f,df,d2f] = FunEx1([X,Y])

where X and Y are the numbers where you want to evaluate the function at.