]> Creatis software - CreaPhase.git/blob - octave_packages/financial-0.4.0/cov2corr.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / financial-0.4.0 / cov2corr.m
1 ## Copyright (C) 2011 Hong Yu <hyu0401@hotmail.com>
2 ##
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
6 ## version.
7 ##
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 ## details.
12 ##
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
15
16 ## -*- texinfo -*-
17 ## @deftypefn {Function File} {[@var{sigma}, @var{corr}] =} cov2corr (@var{cov})
18 ## Convert covariance @var{cov} from input to standard deviation @var{sigma} and
19 ## correlation coefficients @var{corr}.
20 ##
21 ## @seealso{corr2cov, corrcoef, cov, std}
22 ## @end deftypefn
23
24 function [sigma, corr] = cov2corr (cov_m)
25
26   if ( nargin != 1 )
27     print_usage ();
28   elseif ( ndims (cov_m) != 2 || rows(cov_m) != columns(cov_m) )
29     error("covariances must be a NxN matrix");
30   endif
31
32   sigma = diag(cov_m);
33   if ( min(sigma) <= 0 )
34     error("covariance: must have all positive values along the diagonal")
35   endif
36
37   sigma = sqrt(sigma)';
38   corr  = cov_m ./ ( sigma' * sigma );
39
40 endfunction
41
42 %!demo
43 %! cov = [ 0.25 -0.5; -0.5 4.0 ];
44 %! [ sigma, corr ] = cov2corr( cov )
45 %! %--------------------------------------------------
46 %! % Input covariance matrix, output standard deviations and correlation 
47 %! % matrix 
48
49 %!test
50 %! cov = [ 0.25 -0.5; -0.5 4.0 ];
51 %! [sigma, corr] = cov2corr( cov );
52 %! assert( sigma, [0.5 2.0] )
53 %! assert( corr, [1.0 -0.5; -0.5 1.0] );