2
$\begingroup$

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?

$\endgroup$
  • 1
    $\begingroup$ 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. $\endgroup$ – MarcoB Jan 26 '16 at 2:03
  • $\begingroup$ That's a great link, thank you! It's this that I'm really after - the generation step for the random matrices. Fingers crossed! $\endgroup$ – Sprog Jan 26 '16 at 13:56
  • $\begingroup$ Would the function WishartMatrixDistribution help? $\endgroup$ – JimB Jan 2 '17 at 23:29
2
$\begingroup$

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 *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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