Easier way to assign a variable to a row of an array?

Hello Julia users!

I am trying to make a hypothetical dataset of variables X2, Z1, Z2, and ε with some mean and covariance. Using Distributions and Random packages works just fine, but I was wondering if I can assign the variable names and generating an array at the same time.

using LinearAlgebra
using Statistics, Distributions, Random
Random.seed!(123)
μ = [0.0; 0.0; 0.0; 0.0]; # order: X2, Z1, Z2, ε
Σ = [1.0  0.3  -.4  0.5; 
     0.3  1.0  0.4  0.0;
     -.4  0.4  1.0  0.0;
     0.5  0.0  0.0  3.0];
N = 2000;
XZε = rand(MvNormal(μ,Σ),N)
X2 = XZε[1,:]
Z1 = XZε[2,:]
Z2 = XZε[3,:]
ε  = XZε[4,:]

As you can see, variable names X2, Z1, Z2, and ε are assigned after XZε is created. Is there any way I can do that in fewer codes?

Thank you for your input!

If you’re OK with them being views (which might yield better performance actually, depending what you do next),

X2,Z1,Z2,ε = eachrow(XZε)

or if you want bona-fide arrays:

X2,Z1,Z2,ε = collect.(eachrow(XZε))
3 Likes

Thank you for your suggestion! I wanted to use the generated rows to show students different linear instrumental variables estimation. When would view provide better performance, and would it be the case for me too (as in, I am just gonna hcat() some of the rows and do basic linear algebra)?