Effacer les filtres
Effacer les filtres

Derivate using chain rule doesn't work in MATLAB

7 vues (au cours des 30 derniers jours)
Siva Mokkapati
Siva Mokkapati le 8 Nov 2020
Commenté : Star Strider le 11 Nov 2020
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;

Réponses (1)

Star Strider
Star Strider le 8 Nov 2020
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 commentaires
Siva Mokkapati
Siva Mokkapati le 11 Nov 2020
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 le 11 Nov 2020
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.)

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by