Extract the gradient from the deriv command

五迷三道 提交于 2019-12-02 08:07:12

问题


A colleague asked me the following question the other day. In the following piece of code, how do you extract the gradient:

> x=5
> a = eval(deriv(~ x^3, "x"))
> a
[1] 125
attr(,"gradient")
      x
[1,] 75

My answer was

>  attr(a, "gradient")[1]
[1] 75

This syntax seems clunky to me. Is there a better way of extracting the gradient?


回答1:


Not sure these count as better, but:

with(attributes(a), gradient)

or

attributes(a)$gradient

are alternatives that return the attributes as a list from which to select.




回答2:


Though it is no better than your method, you could make a function, grad, that takes a numeric with a gradient attribute and returns the gradient value.

grad = function(x)attr(x,"gradient")[1]

grad(a)

which is now reusable.



来源:https://stackoverflow.com/questions/4034436/extract-the-gradient-from-the-deriv-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!