Derivative with respect to specified element of a vector

For example, I have the following function

function test_fun(state) 
    x, y = state # 2 values
    [x*y^2]
end
state = [2,3]
test_fun(state)

I’d like to find the mixed derivative \frac{d^2f}{dxdy} for vector case.
I can accompish this with the code below

jac₁ = x -> ForwardDiff.jacobian(test_fun, x)
jac₁(state) #  [9 12]
jac₂ = x -> ForwardDiff.jacobian(jac₁, x)
jac₂(state) # [[0; 6], [6, 4]]
out = jac₂(state)[1,2] # 6

but this requires all matrix elements to be computed.
If I try to reduce this procedure as follows

jac₁ = x -> ForwardDiff.jacobian(test_fun, x[1])  # df/dx derivative
println(jac_test_(state))

The error emerges:

MethodError: no method matching jacobian(::typeof(test_fun), ::Int64)

Might be easier to expand out the arguments so you can differentiate w.r.t. each one individually?

julia> dfdx(x,y) = ForwardDiff.derivative(x->test_fun((x,y)),x)
julia> df2dxy(x,y) = ForwardDiff.derivative(y->dfdx(x,y),y)

The error occurs because test_fun has a vector/array argument, while evaluating ForwardDiff.jacobian at x[1] expects a function with a scalar argument.

3 Likes

Yeah, maybe it’s better, thanks