MATLAB中有相关比吗?

Is there a correlation ratio in MATLAB?

Matlab中有计算correlation ratio的函数吗? 这是我尝试做的一个实现,但结果不对。

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;

这是 the Wikipedia page 上的等式:

其中:

  • η为相关比,
  • yx,i 是样本值(x 是 class标签,i样本索引),
  • yx(顶部的条)是 class [=25= 的样本值的平均值]x,
  • y(顶部的条)是所有 classes 和
  • 中所有样本的平均值
  • nx是classx中的样本数。

这就是我将其解释为代码的方式:

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));

循环可以替换为 accumarray