Extract the gradient from the deriv command

后端 未结 2 1064
慢半拍i
慢半拍i 2021-01-23 11:08

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, \         


        
相关标签:
2条回答
  • 2021-01-23 11:36

    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.

    0 讨论(0)
  • 2021-01-23 11:42

    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.

    0 讨论(0)
提交回复
热议问题