Derivate using chain rule doesn't work in MATLAB

7 次查看(过去 30 天)
I am trying to derive the gradient and hessian for a given function. When i directly do the gradient it works well but when I apply chain rule it doesn't works and throws me an error as below
Error using sym/diff (line 70)
Second argument must be a variable or a nonnegative integer specifying the number of differentiations.
Error in EO_a1 (line 12)
dfr = diff(f(x),r(x));
%My MATLAB Code
syms x a b const r(x)
const = (a*x);
r(x) = (const - b);
f(x) = (1/2)*(r(x)^2);
gradient = diff(f(x));
gradient;
hessian = diff(gradient);
hessian;
%gradient applying the chain rule
dfr = diff(f(x),r(x));
dfr;
drx = diff(dfr,x);
drx;

回答(1 个)

Star Strider
Star Strider 2020-11-8
This works for me:
syms f(x) r(x) x
dfr = diff(f(x)*r(x))
producing:
dfr =
f(x)*diff(r(x), x) + r(x)*diff(f(x), x)
that to me appears to bear a strong resemblance to the chain rule for the product of two functions.
I have no idea what you are doing in the last part of your Question.
  2 个评论
Siva Mokkapati
Siva Mokkapati 2020-11-11
Thanks for your response Star Strider.
I have calcuted the 'Gradient' directly in the inital code and in the last part I am trying to calculte gradient using chain rule. (df/dr)*(dr/dx). Ideally both these results should be same. but your suggestion above is giving me completely different answer.
Star Strider
Star Strider 2020-11-11
My pleasure!
There is a gradient and a hessian function in the Symbolic Math Toolbox (both introduced in R2011b).
They may be what you want. (Unless you are not allowed to use them if this is a homework assignment. You can nevertheless use them to check the results of your code.)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Assumptions 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by