- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Get Direct Link
- Report Inappropriate Content
Create correlation matrix
I need to create a correlation matrix to use for some simulations. I want all the off-diagonal elements of the correlation to be the same value. Here is a simple script that does that, but I was wondering if there was a simpler way to do it.
names default to here(1);
// create correlation matrix with specified correlation
k=5;
r=0.9;
corr_matrix=J(k,k,r);
// diagonal elements equal to 1 by adding (1-r)
corr_matrix=corr_matrix + diag(J(k,1,1-r));
This creates the matrix
[1 0.9 0.9 0.9 0.9,
0.9 1 0.9 0.9 0.9,
0.9 0.9 1 0.9 0.9,
0.9 0.9 0.9 1 0.9,
0.9 0.9 0.9 0.9 1]
1 REPLY 1
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Get Direct Link
- Report Inappropriate Content
Re: Create correlation matrix
I'm unaware of a simpler way, but in case you're wanting a simpler way because you're planning on using your code frequently, you could make it into a function, as per the example below. Then, calling it is simpler each time.
//function
make_cm = function ({k,r},
corr_matrix=J(k,k,r);
// diagonal elements equal to 1 by adding (1-r)
corr_matrix=corr_matrix + diag(J(k,1,1-r));
);
//call the function
make_cm (5, .9);