Anthony
Anthony

Reputation: 427

Matlab gradient when missing variables

Let a function f depending of a symbolic variable vector of length 5, x. I want to derive the symbolic gradient of f.

c=1
d=2
x=sym('x',[1 5]);
f=-0.5*log(x(1))+x(1)*0.5*(x(2+d)/x(1)-c)^2
gradient(f)

It gives a vector of length 2 because some variables are missing in f. Is it possible to have a vector of length 5 with 0 when the variable is missing in the function?

Upvotes: 0

Views: 55

Answers (1)

Ander Biguri
Ander Biguri

Reputation: 35525

As easy as telling gradient which are the symbolic variables:

gradient(f,x)

ans =

 (x4/x1 - 1)^2/2 - 1/(2*x1) - (x4*(x4/x1 - 1))/x1
                                                0
                                                0
                                        x4/x1 - 1
                                                0

Upvotes: 1

Related Questions