从 deriv 命令中提取梯度
前几天,一位同事问了我以下问题。在下面的代码中,如何提取渐变:
> x=5
> a = eval(deriv(~ x^3, "x"))
> a
[1] 125
attr(,"gradient")
x
[1,] 75
我的答案是
> attr(a, "gradient")[1]
[1] 75
这种语法对我来说似乎很笨拙。有没有更好的方法来提取梯度?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定这些是否更好,但是:
或
是返回属性作为可供选择的列表的替代方案。
Not sure these count as better, but:
or
are alternatives that return the attributes as a list from which to select.
虽然它并不比您的方法更好,但您可以创建一个函数
grad
,它接受带有渐变属性的数字并返回渐变值。现在可以重复使用。
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.which is now reusable.