何我在matlab中使这段代码更快?

时间:2013-06-14 14:54:35

标签: performance matlab optimization

function [D] = distChiSq( W, X )
%%% find the  Chi2Dist distance between each weight vector and X
% W is nxd
m = size(W,1);  n = size(X,1);
k = size(W,2);
mOnes = ones(1,m); D = zeros(m,n);
for i=1:n
    Xi = X(i,:);  XiRep = Xi( mOnes, : );
    s = XiRep + W;                        /************/
    d = XiRep - W;                        /************/
    D(:,i) = sum( d.^2 ./ (s+eps), 2 );   /************/
end
D = D/2;

这是权重矩阵和数据之间的Chi2距离计算的一部分。标记的行是所有代码中消耗最多的行。有没有办法在MATLAB中更快地完成它?

如果数据是nxm而不是s = nxm, d = nxm而D是保持距离。 n是实例数,m是变量数。

2 个答案:

答案 0 :(得分:5)

哦,这对非常有趣:

s = bsxfun( @plus, permute( X, [1 3 2] ), permute( W, [3 1 2] ) ) + eps;
d = bsxfun( @minus, permute( X, [1 3 2] ), permute( W, [3 1 2] ) ).^2;
D = .5*sum( d./s, 3 );

答案 1 :(得分:2)

替代Shai的好答案:

F = @(a,b) (a-b).^2 ./ (a+b+eps);
D = sum(bsxfun(F, permute(X, [3 1 2]), permute(W, [1 3 2])), 3)/2;