# Generate a simulated covariance matrix

I am working on a problem where one of the input variables is the level of covariance between the entries in a particular matrix. To simulate this problem in Mathematica, I will need to feed my code some simulated covariance matrices.

I will, therefore, need to generate these pretend covariance matrices for dummy data for a range of specified mean levels of covariance.

Is there a way to do this in Mathematica?

• If you want random matrices (according to some definition of random), you may also want to take a look at this discussion over on Cross Validated: How to efficiently generate random positive-semidefinite correlation matrices?. It does not have ready-made Mathematica code though. – MarcoB Jan 26 '16 at 2:03
• That's a great link, thank you! It's this that I'm really after - the generation step for the random matrices. Fingers crossed! – Sprog Jan 26 '16 at 13:56
• Would the function WishartMatrixDistribution help? – JimB Jan 2 '17 at 23:29

I have previously used the following two helper functions to generate the format of covariance and correlation matrices:

covariancematrix[n_] :=
Table[
σ[i] σ[j] ρ[i, j]^(1 - KroneckerDelta[i, j]),
{i, 1, n, 1}, {j, 1, n, 1}
] /. {ρ[i_, j_] :> ρ[j, i] /; i > j}

correlationmatrix[n_] :=
Table[
σ[i] σ[j] ρ[i, j]^(1 - KroneckerDelta[i, j]),
{i, 1, n, 1}, {j, 1, n, 1}
] / Product[σ[i], {i, 1, n, 1}] /. {ρ[i_, j_] :> ρ[j, i] /; i > j}


I could then use the following for instance:

covariancematrix

(* Out:
{{σ^2, ρ[1, 2] σ σ, ρ[1, 3] σ σ, ρ[1, 4] σ σ},
{ρ[1, 2] σ σ, σ^2, ρ[2, 3] σ σ, ρ[2, 4] σ σ},
{ρ[1, 3] σ σ, ρ[2, 3] σ σ, σ^2, ρ[3, 4] σ σ},
{ρ[1, 4] σ σ, ρ[2, 4] σ σ, ρ[3, 4] σ σ, σ^2}}
*)


and I can then substitute appropriate values for standard deviations and correlation coefficients:

covariancematrix;
% /. {σ -> 0.1, σ -> 0.1, σ -> 1000, σ -> 100000};
% /. {ρ[1, 2] -> 0, ρ[1, 3] -> 0, ρ[1, 4] -> 0,
ρ[2, 3] -> 0.4, ρ[2, 4] -> 0.4, ρ[3, 4] -> 0.7}

(* Out:
{{0.01, 0., 0., 0.},
{0., 0.01, 40., 4000.},
{0., 40., 1000000, 7.*10^7},
{0., 4000., 7.*10^7, 10000000000}}
*)


You can check that the matrices thus generated are positive definite, as required:

PositiveDefiniteMatrixQ[%]
(* Out: True *)