1
votes

In matlab, I must compute the symbolic gradient of a function f(x) with x a vector of dimension 5.

x=sym('x',[1,2,3,4,5]);
c=[1 2 4 3 5 3 4 5 4 3 4 34 5 6];
d=[1 0 1 0 0 1 1 1 0 0 0 1 0 1];
f =@(x) sum(-0.5*log(x(1))+x(1)*0.5*(x(2+d)/x(1)-c).^2-log(exp(x(2+d).*c+x(4+d))./(exp(x(2)*c+x(4))+exp(x(3)*c+x(5)))))
grad_f=gradient(f)

The message of error is :

Undefined operator '.'' for input arguments of type 'function_handle'.

Error in gradient>parse_inputs (line 146) f = f.';

Error in gradient (line 48) [f,ndim,loc,rflag] = parse_inputs(f,varargin);

Do you know where is the error?

2
The docs imply that the gradient function takes a numerical vector, not a function handle: mathworks.com/help/matlab/ref/gradient.html - Dan
@Dan there is a symbolic gradient - Yvon
symbolic gradient accepts symbolic function f as input. your definition is a function handle. try removing @(x) mathworks.com/help/symbolic/gradient.html - Yvon
Consider accepting teh answers if they helped you, this will help the community and future people to knwo if something is correct or not - Ander Biguri
@Anthony Hauser: Please upvote and accept ans answer. That is how SO works. - tim

2 Answers

0
votes

I'm only looking at the error message itself here. gradient doesn't like function handles as input.

If I define function f as a pure symbolic without @(x) in the front

f =sum(-0.5*log(x(1))+x(1)*0.5*(x(2+d)/x(1)-c).^2-log(exp(x(2+d).*c+x(4+d))./(exp(x(2)*c+x(4))+exp(x(3)*c+x(5)))))     

then typing gradient gives me a 5x1 array of symbolic expressions.

0
votes

I think you have to specify the symbolc variable you'd want the gradient to be calculated for, and specify f differently (have a look at the example): https://de.mathworks.com/help/symbolic/gradient.html

They specify f without using function handles, because symbolic toolbox will take care of it on its own.

Also have a look at this question: Matlab gradient and hessian computation for symbolic vector function


EDIT: Damn, a little too late after Yvon's comment :-)