]> Creatis software - CreaPhase.git/blob - octave_packages/financial-0.4.0/corr2cov.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / financial-0.4.0 / corr2cov.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{cov} =} corr2cov (@var{sigma}, @var{corr})
18 ## Convert standard deviation @var{sigma} and correlation coefficients @var{corr}
19 ## to covariance @var{cov}.
20 ##
21 ## Note that the rate @var{r} is specified as a fraction (i.e., 0.05,
22 ## not 5 percent).
23 ## @seealso{corrcoef, cov, cov2corr, std}
24 ## @end deftypefn
25
26 function ret = corr2cov (sigma, corr)
27
28   if ( nargin != 2 )
29     print_usage ();
30   elseif ( rows(corr) != columns(corr) || ndims(corr) != 2 )
31     error("correlation coefficients must be a NxN matrix");
32   elseif ( rows(sigma) != 1 || ndims(sigma) != 2 )
33     error("sigma must be a 1xN vector (single row) with the standard deviation values");
34   elseif ( columns(sigma) < columns(1) )
35     error("sigma: must be 1xN \ncorr: must be NxN"); 
36   endif
37
38   sigma = sigma(:);
39   ret   = corr .* (sigma * sigma');
40
41 endfunction
42
43 %!demo
44 %! sigma = [ 0.5 2.0 ];
45 %! corr = [ 1.0 -0.5; -0.5 1.0 ];
46 %! cov = corr2cov( sigma, corr )
47 %! %--------------------------------------------------
48 %! % Input standard deviations and correlation matrix, output covariance 
49 %! % matrix
50
51 %!test
52 %! sigma = [0.5 2.0];
53 %! corr = [1.0 -0.5; -0.5 1.0];
54 %! cov = corr2cov( sigma, corr );
55 %! assert( cov, [ 0.25 -0.5; -0.5 4.0 ] )