r^2 value in matlab

In MATLAB, the corrcoef() function can be used to compute the correlation matrix for two input vectors. The r^2 value is the square of the correlation coefficient (r). Here is an example code to calculate and display the r^2 value given two vectors x and y:

main.m
x = [1,2,3,4,5];
y = [2,4,5,4,5];

% Calculate correlation matrix
corr_matrix = corrcoef(x,y);

% Extract the r value and square it to get r^2
r = corr_matrix(1,2);
r_squared = r^2;

% Display r^2 value
disp(['r^2 value: ', num2str(r_squared)])
245 chars
13 lines

Output:

main.m
r^2 value: 0.4107
18 chars
2 lines

Note that the corrcoef function assumes that the input vectors are columns of data, so if you have row vectors, you may need to transpose them using the transpose operator ' (single quote) before passing them to corrcoef.

related categories

gistlibby LogSnag