Differentiating expressions with both Symbolic arrays and Symbolic variables

Here’s a MWE of what I want to work but doesn’t.

using Symbolics

K = 3
@variables M[1:K, 1:K]
x1 = Symbolics.variables(:x1, 1:K)
x2 = Symbolics.variables(:x2, 1:K)
result = vcat(M * x1, M * x2)
Jx1 = Symbolics.jacobian(result, x1)

My understanding of the error is that, because M is a Symbolic matrix while x1 and x2 are vectors of Symbolic variables, Mx1 and Mx2 have type SymbolicUtils.BasicSymbolicImpl.var"typeof(BasicSymbolicImpl)"{SymReal}. I assume that Symbolics doesn’t know how to tell that the result is a vector, so when I call vcat on these two objects, it doesn’t work. Now, a simple solution for me is to simply differentiate each expression on their own, but it’d be nice if I didn’t have to do that. I couldn’t figure out if Symbolics.jl has this functionality or not already.

We don’t hae symbolic array calculus yet, so it’ll need to scalarize to differentiate.

You can do it in FastDifferentiation:

julia> M = make_variables(:M,3,3)
3×3 Matrix{FastDifferentiation.Node}:
 M1_1  M1_2  M1_3
 M2_1  M2_2  M2_3
 M3_1  M3_2  M3_3

julia> x1 = make_variables(:x1,3)
3-element Vector{FastDifferentiation.Node}:
 x11
 x12
 x13

julia> x2 = make_variables(:x2,3)
3-element Vector{FastDifferentiation.Node}:
 x21
 x22
 x23

julia> result = vcat(M*x1,M*x2)
6-element Vector{FastDifferentiation.Node}:
 (((M1_1 * x11) + (M1_2 * x12)) + (M1_3 * x13))
 (((M2_1 * x11) + (M2_2 * x12)) + (M2_3 * x13))
 (((M3_1 * x11) + (M3_2 * x12)) + (M3_3 * x13))
 (((M1_1 * x21) + (M1_2 * x22)) + (M1_3 * x23))
 (((M2_1 * x21) + (M2_2 * x22)) + (M2_3 * x23))
 (((M3_1 * x21) + (M3_2 * x22)) + (M3_3 * x23))

julia> Jx1 = jacobian(result,x1)
6×3 Matrix{FastDifferentiation.Node}:
 M1_1    M1_2    M1_3
 M2_1    M2_2    M2_3
 M3_1    M3_2    M3_3
    0.0     0.0     0.0
    0.0     0.0     0.0
    0.0     0.0     0.0