Re: correlated random vector
- To: mathgroup at smc.vnet.net
- Subject: [mg63948] Re: correlated random vector
- From: "Ray Koopman" <koopman at sfu.ca>
- Date: Tue, 24 Jan 2006 01:30:34 -0500 (EST)
- References: <dqsp65$cbj$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Jan Schmedes wrote:
> Dear group,
>
> given a vector of observed data x i would like to create a vector with
> uniform distributed random numbers y that is correlated with the observed
> vector, that is, corr(x,y)=r for a given r, say 0.6. Is that possible and
> how could i do that in Mathematica?
>
> Regards
>
> Jan
In general it can't be done exactly, but the following approach will
give the desired correlation while coming as close to uniformity as
it can. However, the code is specific to n = 6 because general code
would be too opaque.
In[1]:= <<Statistics`
In[2]:= unicorr[x_List /; Length@x == 6, r_ /; Abs@r < 1] :=
Block[{n = Length@x, z},
z = Rest @ First @ QRDecomposition @ Transpose @ Join[
{Table[1.,{n}], x}, Table[Random[],{n-2},{n}]];
If[Negative[x.z[[1]]], z[[1]] *= -1]; Prepend[Last /@ Last @
NMinimize[{#.#&@ListConvolve[{1,-2,1},Sort[{r,w1,w2,w3,w4}.z]],
#.#&@{w1,w2,w3,w4} == Evaluate[1.-r^2]},
{w1,w2,w3,w4}], r].z]
In[3]:= x = Table[Random[],{n = 6}]
Out[3]= {0.742682,0.151194,0.106214,0.318151,0.748664,0.78995}
In[4]:= y = unicorr[x, .6]
Out[4]= {0.135047,-0.435794,-0.552032,0.477698,-0.119517,0.494598}
In[5]:= Correlation[x,y]
Out[5]= 0.6