Converting Covariance Matrix to Correlation Matrix

조회 수: 7 (최근 30일)
Jim Moser
Jim Moser 2014년 10월 13일
답변: Matt J 2014년 10월 24일
I know of MATLAB function to convert a covariance matrix to a correlation matrix but I'm a teacher and want to demonstrate matrix manipulation. I can do the conversion using for loops as below but can't figure out how to do this more elegantly (using matrix operations).
d=diag(cov).^.5;
for i=1:length(cov)
for j=1:length(cov)
corr(i,j)=cov(i,j)./(d(i)*d(j));
end
end
Thanks in advance for any help.

답변 (3개)

Peter Perkins
Peter Perkins 2014년 10월 14일
Jim, if you mean, "matrix operations" as in "something out of a math book", then you can right and left multiply by diag(d), where d is 1./sqrt(diag(C)). If you mean "MATLAB matrix operations", then you can use ./ with d*d'.
You might find it interesting to look at the guts of corrcoef, where the code takes a bit more care.
Hope this helps.
  댓글 수: 2
Jim Moser
Jim Moser 2014년 10월 14일
Peter, yes I saw that suggested elsewhere and it puzzled me. If the covariance matrix is 3x3, then left multiplying it by the transpose of the diagonal gives a 1x3 and multiplying the diagonal by that gives a 1x1. The code I listed gives a 3x3 correlation matrix.
And yes by "matrix operations" I was hoping for something that would match a standard text treatment.
Peter Perkins
Peter Perkins 2014년 10월 24일
Sorry, I think I meant diag(1./sqrt(diag(C))). If C is a 3x3 cov matrix, then diag(C) is a vector, and diag(1./sqrt(diag(C))) is a 3x3 diagonal matrix.

댓글을 달려면 로그인하십시오.


James Tursa
James Tursa 2014년 10월 24일
편집: James Tursa 2014년 10월 24일
A method using outer product and element-wise divide:
d = sqrt(diag(cov));
corr = cov./(d*d');
  댓글 수: 1
Jim Moser
Jim Moser 2014년 10월 24일
Thank you, exactly what I was sure was there but couldn't see.

댓글을 달려면 로그인하십시오.


Matt J
Matt J 2014년 10월 24일
corr=bsxfun(@rdivide,cov, d(:));
corr=bsxfun(@rdivide, corr,d(:).');

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by