0
$\begingroup$

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?

$\endgroup$
5
  • $\begingroup$ Try matrix KroneckerProduct[vector, vector] or vector matrix.DiagonalMatrix[SparseArray[vector]]. $\endgroup$ Apr 12, 2021 at 15:43
  • $\begingroup$ @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. $\endgroup$
    – Quiver
    Apr 12, 2021 at 15:53
  • $\begingroup$ @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! $\endgroup$
    – Quiver
    Apr 12, 2021 at 16:02
  • $\begingroup$ "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. $\endgroup$ Apr 12, 2021 at 16:09
  • $\begingroup$ Ah, you are taking about a $1 \times 10$ vector. Then just use Flatten : matrix KroneckerProduct[Flatten[vector], Flatten[vector]]. $\endgroup$ Apr 12, 2021 at 16:14

1 Answer 1

2
$\begingroup$

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

$\endgroup$
1
  • $\begingroup$ 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! $\endgroup$
    – Quiver
    Apr 12, 2021 at 16:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.