[matlab] Correlation between two vectors?

I have two vectors:

A_1 = 

      10
      200
      7
      150

A_2 = 
      0.001
      0.450
      0.0007
      0.200

I would like to know if there is correlation between these two vectors.

I could subtract to each value the mean of the vector and than do:

  A_1' * A_2

Are there any better ways?

This question is related to matlab statistics

The answer is


To perform a linear regression between two vectors x and y follow these steps:

[p,err] = polyfit(x,y,1);   % First order polynomial
y_fit = polyval(p,x,err);   % Values on a line
y_dif = y - y_fit;          % y value difference (residuals)
SSdif = sum(y_dif.^2);      % Sum square of difference
SStot = (length(y)-1)*var(y);   % Sum square of y taken from variance
rsq = 1-SSdif/SStot;        % Correlation 'r' value. If 1.0 the correlelation is perfect

For x=[10;200;7;150] and y=[0.001;0.45;0.0007;0.2] I get rsq = 0.9181.

Reference URL: http://www.mathworks.com/help/matlab/data_analysis/linear-regression.html


Try xcorr, it's a built-in function in MATLAB for cross-correlation:

c = xcorr(A_1, A_2);

However, note that it requires the Signal Processing Toolbox installed. If not, you can look into the corrcoef command instead.


For correlations you can just use the corr function (statistics toolbox)

corr(A_1(:), A_2(:))

Note that you can also just use

corr(A_1, A_2)

But the linear indexing guarantees that your vectors don't need to be transposed.