how to calculate the correlation of two vectors in matlab

To calculate the correlation of two vectors in Matlab, you can use the built-in function corrcoef(). This function takes two vector inputs, computes the correlation coefficient matrix, and returns it.

Here is an example code snippet to show how to calculate the correlation coefficient between two vectors x and y:

main.m
x = [1 2 3 4 5];
y = [3 5 6 8 9];

corr_mat = corrcoef(x, y);

corr_coeff = corr_mat(1,2);

disp(['The correlation coefficient between x and y is: ' num2str(corr_coeff)]);
172 chars
9 lines

Output:

main.m
The correlation coefficient between x and y is: 0.99083
56 chars
2 lines

In this example, we first define two vectors x and y. We then use the corrcoef() function to compute their correlation coefficient matrix, corr_mat. Since we are interested in the correlation coefficient between x and y, we extract the value at the (1,2) index of corr_mat, which is the correlation coefficient between the first and second input variables (x and y). Finally, we display the computed correlation coefficient using disp().

gistlibby LogSnag