# 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. Commented Jan 26, 2016 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! Commented Jan 26, 2016 at 13:56
• Would the function WishartMatrixDistribution help?
– JimB
Commented Jan 2, 2017 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[4]

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


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

covariancematrix[4];
% /. {σ[1] -> 0.1, σ[2] -> 0.1, σ[3] -> 1000, σ[4] -> 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 *)