# Derivative with respect to specified element of a vector

**URL:** https://discourse.julialang.org/t/derivative-with-respect-to-specified-element-of-a-vector/53045
**Category:** Numerics
**Tags:** differentiation
**Created:** [January 8, 2021, 2:50pm UTC](https://discourse.julialang.org/t/derivative-with-respect-to-specified-element-of-a-vector/53045 "2021-01-08T14:50:12Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Sunny](https://avatars.discourse-cdn.com/v4/letter/s/7c8e57/32.png) [@Sunny](https://discourse.julialang.org/u/Sunny)
#### Post date: [January 8, 2021, 2:50pm UTC](https://discourse.julialang.org/t/derivative-with-respect-to-specified-element-of-a-vector/53045/1 "2021-01-08T14:50:12Z")

</div>

For example, I have the following function

```julia
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

```julia
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

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

```

The error emerges:

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

```

---

<div class="post-metadata">

### Author: ![jlchan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jlchan/32/10958_2.png) [@jlchan](https://discourse.julialang.org/u/jlchan)
#### Post date: [January 8, 2021, 3:21pm UTC](https://discourse.julialang.org/t/derivative-with-respect-to-specified-element-of-a-vector/53045/2 "2021-01-08T15:21:55Z")

</div>

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

```julia
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.

---

<div class="post-metadata">

### Author: ![Sunny](https://avatars.discourse-cdn.com/v4/letter/s/7c8e57/32.png) [@Sunny](https://discourse.julialang.org/u/Sunny)
#### Post date: [January 8, 2021, 3:34pm UTC](https://discourse.julialang.org/t/derivative-with-respect-to-specified-element-of-a-vector/53045/3 "2021-01-08T15:34:58Z")

</div>

Yeah, maybe it’s better, thanks
