cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
The Discovery Summit 2025 Call for Content is open! Submit an abstract today to present at our premier analytics conference.
See how to use to use Text Explorer to glean valuable information from text data at April 25 webinar.
Choose Language Hide Translation Bar
View Original Published Thread

Create correlation matrix

MathStatChem
Level VII

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


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);