how to calculate the correlation matrix in matlab

36,080

You can use either CORR or CORRCOEF functions. Both functions will return the same correlation matrix (the results may differ for very low p-values depending on your MATLAB release).

You need to take care of NaN values. Both have parameter 'rows'. Here is a quote from documentation with possible parameter values:

Either 'all' (default) to use all rows, 'complete' to use rows with no NaN values, or 'pairwise' to compute R(i,j) using rows with no NaN values in either column i or j.

If you have NaN elements setting 'rows' to 'all ' will use all the elements, but you will get NaN as a results. 'complete' will use only rows without NaN in any columns. 'pairwise' is what I usually use, it will remove the rows with NaN for each comparison independently.

So, if you x1, x2 and x3 are column vectors to get correlation matrix use:

[rho, pval] = corr([x1, x2, x3], 'rows','pairwise');

If your variables are columns in one matrix x:

[rho, pval] = corr(x, 'rows','pairwise');

Or use corrcoef instead of corr. CORR can also calculate other than Pearson correlation, like Spearman or Kendall. Specify it with 'type' parameter.

Share:
36,080
user2238514
Author by

user2238514

Updated on July 30, 2022

Comments

  • user2238514
    user2238514 over 1 year

    I have a data set which is showed below;

    x1          x2          x3
    -10.593017  NaN         NaN
    -10.300049  3.624823938 NaN
    -11.776855  3.707569866 NaN
    -10.342041  3.770059949 NaN
    -19.416992  3.819520417 6.516808442
    -12.051026  3.898067841 6.753639662
    NaN         3.687338806 6.317082898
    NaN         NaN         6.226243427
    

    can you tell me how to calculate the correlation matrix? can 'corrcoef' be used in the program? or there are other methods. please tell me. thank you!

    • Black Maggie
      Black Maggie about 11 years
      Welcome to SO. Please reformat your question so that it fits the SO FAQ standards. stackoverflow.com/faq
    • Autonomous
      Autonomous about 11 years
      You can calculate correlation between x1 and x2 as corr2(x1,x2). Similarly you can calculate for other pairs. Is this what you want? You will have to take care of NaNs