# Derivative of Kronecker product by vector in Mathematica

I'm struggling with the following problem. It is necessary to find the derivative expression with respect to the vector $$u$$:

$$r(u,v)=[(u-v)(u-v)^T]\begin{pmatrix} 1\\ 1\\ 1 \end{pmatrix}=[(u-v)\otimes (u-v)]\begin{pmatrix} 1\\ 1\\ 1 \end{pmatrix}$$

If we use the results from the topic https://math.stackexchange.com/questions/3112634/derivative-of-kronecker-product-of-vector-with-itself, we get:

$$\frac{dr}{du}=[(\big(I\otimes(v-u)\big) + \big((v-u) \otimes I\big))]\begin{pmatrix} 1\\ 1\\ 1 \end{pmatrix}$$

When I try to figure out the bracketed expression using Mathematica, I get an error. As far as I understand, something is wrong in the original formula, because the summed arrays have different dimensions.

I need help from more experienced professionals. I would be glad and grateful for help.

Clear["Derivative"]

ClearAll["Global*"]

u = {a, b, c};

v = {x, y, z};

KroneckerProduct[u - v, u - v] // MatrixForm;

(KroneckerProduct[DiagonalMatrix[{1, 1, 1}], v - u] +
TensorProduct[v - u, DiagonalMatrix[{1, 1, 1}]]) // MatrixForm

• Use Dimensions to diagnose the issue - your KroneckerProduct is dimension {3, 9} but the TensorProduct is dimension {3, 3, 3}. Jul 15, 2021 at 12:25
• @flinty and what can i do? I don't understand
– dtn
Jul 15, 2021 at 12:26

One tricky thing to keep in mind is that in Mathematica a vector is always 1 dimensional, so it's not automatically treated as an n by 1 matrix. Because of this, the distinction between column and row vectors disappears and this affects some matrix operations.

For example, consider:

u = {a, b, c};
KroneckerProduct[u, IdentityMatrix[3]] // Dimensions
KroneckerProduct[IdentityMatrix[3], u] // Dimensions


{9, 3}

{3, 9}

Because of the different dimensions, you can't add the two matrices. Instead, turn u into a column vector explicitly:

u = List /@ {a, b, c};
KroneckerProduct[u, IdentityMatrix[3]] // Dimensions
KroneckerProduct[IdentityMatrix[3], u] // Dimensions
`

{9, 3}

{9, 3}

Now you can add the results together.