1

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?

NLV
  • 21,141
  • 40
  • 118
  • 183
Anthony
  • 377
  • 2
  • 6
  • 13
  • The docs imply that the `gradient` function takes a numerical vector, not a function handle: http://www.mathworks.com/help/matlab/ref/gradient.html – Dan May 09 '16 at 15:42
  • 1
    @Dan there is a symbolic `gradient` – Yvon May 09 '16 at 15:45
  • 3
    symbolic `gradient` accepts symbolic function `f` as input. your definition is a function handle. try removing `@(x)` http://www.mathworks.com/help/symbolic/gradient.html – Yvon May 09 '16 at 15:46
  • 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 May 10 '16 at 10:41
  • @Anthony Hauser: Please upvote and accept ans answer. That is how SO works. – tim May 18 '16 at 18:29

2 Answers2

0

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 :-)

tim
  • 9,896
  • 20
  • 81
  • 137
0

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.

Yvon
  • 2,903
  • 1
  • 14
  • 36