[Tutor] correlation matrix

Noufal Ibrahim noufal at airtelbroadband.in
Sat Jul 21 20:54:52 CEST 2007


Beanan O Loughlin wrote:
> hi all,
> 
> I am new to python, and indeed to programming, but i have a question 
> regarding correlation matrices.
> 
> If i have a column vector
> 
> x=[1;2;3;4;5]
> 
> and its transpose row vector
> 
> xt=[1,2,3,4,5]
> 
> is there a simple way in python to create a 5x5 correlation matrix, 
> obviously symmetric and having 1's on the diagonal?

My knowledge of matrix algebra and statistics is quite rusty but from a 
programming perspective, I'd understand this like so.

You want a 5x5 table of values (correlations in this case) computed from 
all permutations of 2 variables selected from a set of 5 elements.

so, you'd want something like
cor(1,1)   cor(1,2)   cor(1,3) ....
cor(2,1)   cor(2,2)   cor(2,3) ...
.
.
.
Correct?


If so, I think this might be what you're looking for (I've put some 
comments to make it explanatory).

 >>> import Numeric
 >>> x=[1,2,3]
 >>> ret = []
 >>> for i in x:
...  ret1=[]
...  for j in x:  # Since we're correlating an array with itself.
...   ret1.append((i,j,))  # You'd need to call the actual correlation 
function here rather than just say (i,j)
...  ret.append(ret1)
...
 >>> Numeric.array(ret)
array([[[1, 1],
         [1, 2],
         [1, 3]],
        [[2, 1],
         [2, 2],
         [2, 3]],
        [[3, 1],
         [3, 2],
         [3, 3]]])
 >>>

The "Numeric"  module has fast implementations of matrices and other 
such constructs.
I'm quite sure that this thing which I've written above can be improved 
on but I think it would do your work for you.


-- 
~noufal


More information about the Tutor mailing list