# Vector of vector of gradients

**URL:** https://discourse.julialang.org/t/vector-of-vector-of-gradients/113348
**Category:** Numerics
**Tags:** question
**Created:** [April 22, 2024, 4:35pm UTC](https://discourse.julialang.org/t/vector-of-vector-of-gradients/113348 "2024-04-22T16:35:56Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Domenico\_Lahaye](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/domenico_lahaye/32/203728_2.png) [@Domenico\_Lahaye](https://discourse.julialang.org/u/Domenico_Lahaye)
#### Post date: [April 22, 2024, 4:35pm UTC](https://discourse.julialang.org/t/vector-of-vector-of-gradients/113348/1 "2024-04-22T16:35:56Z")

</div>

I am to extend the scalar case of a gradient of a function, i.e.,

```julia
foo = Vector{Function}(undef,2)
gnu = Vector{Function}(undef,2)
foo[1] = (x,y) -> x+y 
foo[2] = (x,y) -> x-y 
A = [1. 2.; 3. 4.]
gnu = (x,y) -> B * [foo[1](x,y),foo[2](x,y)]

```

to the case of a vector of gradient of functions

```julia
ndof = 3 
foo = Vector{Vector}(undef,ndof)
gnu = Vector{Vector}(undef,ndof)
for i=1:ndof 
    foo[i] = Vector{Function}(undef,2)
    gnu[i] = Vector{Function}(undef,2)
end 
foo[1][1] = (x,y) -> x+y
foo[1][2] = (x,y) -> x-y
foo[2][1] = (x,y) -> 2*x+2*y  
foo[2][2] = (x,y) -> 2*x-2*y
foo[3][1] = (x,y) -> 3*x+3*y  
foo[3][2] = (x,y) -> 3*x-3*y 
A = [1. 2.; 3. 4.]
for i=1:ndof 
    gnu[i][:] .= (x,y) -> A * [foo[i][1](x,y);foo[i][2](x,y)]
end 

```

Help is appreciated.

---

<div class="post-metadata">

### Author: ![gdalle](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gdalle/32/27854_2.png) [@gdalle](https://discourse.julialang.org/u/gdalle)
#### Post date: [April 22, 2024, 5:22pm UTC](https://discourse.julialang.org/t/vector-of-vector-of-gradients/113348/2 "2024-04-22T17:22:36Z")

</div>

Is there something that doesn’t work with your code? Why do you need help?

As a side note, a `Vector{Function}` has an abstract element type and so it might be rather slow. Depending on your specific problem, a more appropriate structure can speed things up (for instance if all your functions are linear combinations you can store the coefficients instead of the anonymous function objects)

---

<div class="post-metadata">

### Author: ![Domenico\_Lahaye](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/domenico_lahaye/32/203728_2.png) [@Domenico\_Lahaye](https://discourse.julialang.org/u/Domenico_Lahaye)
#### Post date: [April 22, 2024, 6:37pm UTC](https://discourse.julialang.org/t/vector-of-vector-of-gradients/113348/3 "2024-04-22T18:37:08Z")

</div>

@gdalle : thx!

The code works indeed. I was testing incorrectly.

I will worry about performance later.
