home


The following code is provided as is with no warranties express or implied or statutory or whatever, standard disclaimers apply, use at your own risk, yatta, yatta, yatta. If you find any problems, please make a comment here.

Here's a little Scilab function for calculating a Correlation Matrix.

function [y] = correlation(m)

    // copy source
    x = m;

    // subtract mean and scale appropriately

    [nrows,ncols] = size(m);

    for i=1:ncols

        mu = mean(x(:,i));

        sgi = 1.0 / (sqrt(nrows-1) * stdev(x(:,i)));

        x(:,i) = (x(:,i) - mu) * sgi;

    end


    // x'x

    y = x' * x;

endfunction



And here's a shorter version...  (varcovar( ) is here)


function [y] = correlation(m)

    vc = varcovar(m);


    t = inv(diag(sqrt(diag(vc))));


    y = t*vc*t;

endfunction


Example with NIST data

-->Z=[7 4 3
-->4 1 8
-->6 3 5
-->8 6 1
-->8 5 7
-->7 2 9
-->5 3 3
-->9 5 8
-->7 4 5
-->8 2 2];

-->correlation(Z)
ans =

  1.            0.6686573   - 0.1013137
  0.6686573     1.          - 0.2879277
- 0.1013137   - 0.2879277     1.

Note: If you're concerned with issues of stability and performance, see Knuth, this Wikipedia entry, etc.