I have two matrices I want to add, and one of the matrices is a tensor product of two vectors. I've used a SetDelayed to define the summed matrix, because I want to evaluate it for different values of these vectors. However, when I try to evaluate it using a replacement, I get a new array with the wrong dimensionality. Here's a minimal(ish?) example:
mat := DiagonalMatrix[{1, 1, 1, 1}] + TensorProduct[vec, vec]
Then using a replace gives me something horrible:
mat /. vec -> {2, 2, 2, 2}
{{{{5, 5, 5, 5}, {5, 5, 5, 5}, {5, 5, 5, 5}, {5, 5, 5, 5}}, {{4, 4, 4,
4}, {4, 4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4, 4}}, {{4, 4, 4, 4}, {4,
4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4, 4}}, {{4, 4, 4, 4}, {4, 4, 4,
4}, {4, 4, 4, 4}, {4, 4, 4, 4}}}, {{{4, 4, 4, 4}, {4, 4, 4,
4}, {4, 4, 4, 4}, {4, 4, 4, 4}}, {{5, 5, 5, 5}, {5, 5, 5, 5}, {5,
5, 5, 5}, {5, 5, 5, 5}}, {{4, 4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4,
4}, {4, 4, 4, 4}}, {{4, 4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4, 4}, {4,
4, 4, 4}}}, {{{4, 4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4,
4}}, {{4, 4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4,
4}}, {{5, 5, 5, 5}, {5, 5, 5, 5}, {5, 5, 5, 5}, {5, 5, 5,
5}}, {{4, 4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4,
4}}}, {{{4, 4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4,
4}}, {{4, 4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4,
4}}, {{4, 4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4, 4}, {4, 4, 4,
4}}, {{5, 5, 5, 5}, {5, 5, 5, 5}, {5, 5, 5, 5}, {5, 5, 5, 5}}}}
But a block (or setting vec={2,2,2,2}) gives the correct behavior:
Block[{vec = {2, 2, 2, 2}}, mat]
{{5, 4, 4, 4}, {4, 5, 4, 4}, {4, 4, 5, 4}, {4, 4, 4, 5}}
(Sorry, not sure if I typed in the output correctly here.)
What's going on?
DiagonalMatrix[{1, 1, 1, 1}] + TensorProduct[vec, vec]) symbolically. Try that and you'll see exactly what's going wrong. – Szabolcs Jun 02 '14 at 15:35