cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
  • Register to attend Discovery Summit 2025 Online: Early Users Edition, Sept. 24-25.
  • New JMP features coming to desktops everywhere this September. Sign up to learn more at jmp.com/launch.
Choose Language Hide Translation Bar
MathStatChem
Level VII

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

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

Recommended Articles