# Gradient to jacobian in type stable way with ForwardDiff

**URL:** <https://discourse.julialang.org/t/gradient-to-jacobian-in-type-stable-way-with-forwarddiff/107015>\
**Category:** General Usage\
**Tags:** forwarddiff, type-stability\
**Created:** [December 1, 2023, 8:01pm UTC](https://discourse.julialang.org/t/gradient-to-jacobian-in-type-stable-way-with-forwarddiff/107015 "2023-12-01T20:01:19Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![JonasWickman](https://avatars.discourse-cdn.com/v4/letter/j/9de0a6/32.png) [@JonasWickman](https://discourse.julialang.org/u/JonasWickman)\
**Post date:** [December 1, 2023, 8:01pm UTC](https://discourse.julialang.org/t/gradient-to-jacobian-in-type-stable-way-with-forwarddiff/107015/1 "2023-12-01T20:01:19Z")

</div>

I have a function `f(x,y)` where `x` and `y` are both vectors, and I would like to calculate the matrix of mixed partials. The following works but is not type stable

```julia
using ForwardDiff
f(x,y) = sum(x)*sum(y)
x0 = [1.0, 2.0, 3.0]
y0 = [-1.0, -2.0, -3.0, -4.0]
fx = y -> ForwardDiff.gradient(x -> f(x, y), x0)
fxy = ForwardDiff.jacobian(fx, y0)

```

Normally, the way I make gradients and Jacobians type stable with ForwardDiff is to preallocate the output vector or matrix, but since the Jacobian computation needs to differentiate throught the gradient computation I cannot figure out the correct way to do it.

The function `f` above is just an example, in my actual code I need to get this to work for any function (within reason) of two vectors `x` and `y`. Regrettably, some instances will be too large for StaticArrays to be useful, which otherwise works fine for small systems.
