Felippe Trigueiro
Felippe Trigueiro

Reputation: 109

Is there a correlation ratio in MATLAB?

Is there any function in Matlab which calculates the correlation ratio? Here is an implementation I tried to do, but the results are not right.

function cr = correlation_ratio(X, Y, L)
ni = zeros(1, L);
sigmai = ni;

for i = 0:(L-1)
   Yn = Y(X == i);
   ni(1, i+1) = numel(Yn);
   m = (1/ni(1, i+1))*sum(Yn);
   sigmai(1, i+1) = (1/ni(1, i+1))*sum((Yn - m).^2);
end
n = sum(ni);
prod = ni.*sigmai;
cr = (1-(1/n)*sum(prod))^0.5;

Upvotes: 1

Views: 272

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60680

This is the equation on the Wikipedia page:

correlation ratio

where:

  • η is the correlation ratio,
  • yx,i are the sample values (x is the class label, i the sample index),
  • yx (with the bar on top) is the mean of sample values for class x,
  • y (with the bar on top) is the mean for all samples across all classes, and
  • nx is the number of samples in class x.

This is how I interpreted it into code:

function eta = correlation_ratio(X, Y)
X = X(:); % make sure we've got column vectors, simplifies things below a bit
Y = Y(:);
L = max(X);
mYx = zeros(1, L+1); % we'll write mean per class here
nx = zeros(1, L+1);  % we'll write number of samples per class here
for i = unique(X).'
   Yn = Y(X == i);
   if numel(Yn)>1
      mYx(i+1) = mean(Yn);
      nx(i+1) = numel(Yn);
   end
end
mY = mean(Y);        % mean across all samples
eta = sqrt(sum(nx .* (mYx - mY).^2) / sum((Y-mY).^2));

The loop could be replaced with accumarray.

Upvotes: 1

Related Questions