# ForwardDiff on keyword argument?

I have a function with parameters as a keyword argument, say:

f(x;p = [1,2,1]) = p[1]*x^2 + p[2]*x + p[3]


How do I compute the gradient g(x,p) = \frac{\partial f(x;p)}{\partial p}?

make a closure p -> f(x; p=p) and differentiate that (for some given x).

1 Like

Thanks. Does that mean that I need to define this anonymous function each time I change x? (In MATLAB, I would need to do that, as far as I recall.)

In other words, do I need to specify a numeric value for x before I make the closure you suggest?

A simple test case:

julia> using ForwardDiff;
julia> f(x;p=[1,2,1]) = p[1]*x^2 + p[2]*x + p[3];
julia> h = p -> f(x;p=p)
julia> g = p -> ForwardDiff.gradient(h,p)
julia> x = 3;
julia> g([1,2,3.])
3-element Array{Float64,1}:
9.0
3.0
1.0
julia> x = 4;
julia> g([1,2,3])
3-element Array{Int64,1}:
16
4
1


Nice!

1 Like