# Particular element-wise multiplication between matrix and vectors

I have the following formula to implement $$\Sigma_{ij} = \rho_{ij}\sigma_i\sigma_j$$ where no implicit summation is implied. I have both the $$\sigma$$ vector and the $$\rho$$ matrix and I want to calculate the $$\Sigma$$ matrix.

To be pedantic what i need is a way to find the elements of the matrix $$\Sigma$$ such that, take for example the element $$(1,2)$$, this is given by the normal multiplication $$\Sigma_{12} = \rho_{12}\sigma_1\sigma_2$$

Specifically the vector is a $$1\times 10$$ vector and the matrix is $$10\times 10$$. At the end I want another $$10\times10$$ matrix defined as before.

How can I do this?

• Try matrix KroneckerProduct[vector, vector] or vector matrix.DiagonalMatrix[SparseArray[vector]]. Apr 12, 2021 at 15:43
• @HenrikSchumacher both of them seem to not work. In particular the KroneckerProduct of the two vectors yields a $1\times 100$ column vector which cannot be multiplied by the matrix. In the second case I'm not sure what's going on. Apr 12, 2021 at 15:53
• @HenrikSchumacher Your answer sparked something in my head: I converted the vector to a diagonal matrix with diagonal elements the elements of the vector and then multiplied row-by-columns diagMatrix.Matrix.diagMatrix and I seem to get a sensible answer! Apr 12, 2021 at 16:02
• "both of them seem to not work." What are you talking about? They work (see below). KroneckerProduct[vector, vector] is a $10 \times 10$ matrix. Apr 12, 2021 at 16:09
• Ah, you are taking about a $1 \times 10$ vector. Then just use Flatten : matrix KroneckerProduct[Flatten[vector], Flatten[vector]]. Apr 12, 2021 at 16:14

Just too long for a comment.

n = 1000;
matrix = RandomReal[{-1, 1}, {n, n}];
vector = RandomReal[{-1, 1}, {n}];

A0 = Table[matrix[[i, j]] vector[[i]] vector[[j]], {i, 1, n}, {j, 1, n}]; //
AbsoluteTiming // First
A1 = matrix KroneckerProduct[vector, vector]; // AbsoluteTiming // First
A2 = vector matrix.DiagonalMatrix[SparseArray[vector]]; //
AbsoluteTiming // First


1.32595

0.006415

0.006203

This shows that one should avoid Table if possible.

Max[Abs[A0 - A1]]
Max[Abs[A0 - A2]]


1.11022*10^-16

1.11022*10^-16

• Yes, the first one worked pretty well! It gave the same result as per the solution I gave in the comments. Thank you very much! Apr 12, 2021 at 16:25