MATLAB中有效的元素差异

时间:2016-04-30 14:29:19

标签: performance matlab difference

目前有一个bunch of pages关于在MATLAB中有效计算成对距离(有些甚至是我!)。我希望做一些与众不同的事情。

而不是计算两个矩阵中行对之间的总距离,比如XY

X = [1 1 1; 2 2 2];
Y = [1 2 3; 4 5 6];

我想计算一个3维矩阵,存储每对行之间的原始列方差。在上面的例子中,这个矩阵将有两行(对于X中的2个观测值),3列和第3维中的2个切片(对于Y中的2个观测值):

diffs(:,:,1) =

     0    -1    -2
     1     0    -1


diffs(:,:,2) =

    -3    -4    -5
    -2    -3    -4
到目前为止,我已经提出了两种方法来完成这个作为一般情况,但我想找到一些优雅,透明和高效的东西。

Repmat + Permute Approach

% Set up data
X = rand(100,10);
Y = rand(200,10);

timer = tic;
X_tiled = repmat(X,[1 1 size(Y,1)]);
Y_tiled = repmat(permute(Y,[3,2,1]),[size(X,1),1,1]);
diffs = X_tiled - Y_tiled;
toc(timer)
% Elapsed time is 0.001883 seconds.

For-Loop Approach

timer = tic;
diffs = zeros(size(X,1),size(X,2),size(Y,1));
for i = 1:size(X,1)
    for  j =1:size(Y,1)
        diffs(i,:,j) = X(i,:) - Y(j,:);
    end
end
toc(timer)
% Elapsed time is 0.028620 seconds.

有没有其他人比我得到的更好?

1 个答案:

答案 0 :(得分:3)

repmat上使用under-the-hood broadcasting后,您可以使用bsxfun替换permute的混乱Y,将第一个维度发送到第三个位置,保持第二个维度,以匹配X的第二个维度。这可以通过permute(Y,[3 2 1]来实现。因此,解决方案是 -

diffs = bsxfun(@minus,X,permute(Y,[3 2 1]))

<强>基准

基准代码 -

% Set up data
X = rand(100,10);
Y = rand(200,10);

% Setup number of iterations
num_iter = 500;

%// Warm up tic/toc.
for iter = 1:50000
    tic(); elapsed = toc();
end

disp('---------------- With messy REPMAT')
timer = tic;
for itr = 1:num_iter
    X_tiled = repmat(X,[1 1 size(Y,1)]);
    Y_tiled = repmat(permute(Y,[3,2,1]),[size(X,1),1,1]);
    diffs = X_tiled - Y_tiled;
end
toc(timer)

disp('---------------- With sassy BSXFUN')
timer = tic;
for itr = 1:num_iter
    diffs1 = bsxfun(@minus,X,permute(Y,[3 2 1]));
end
toc(timer)

输出 -

---------------- With messy REPMAT
Elapsed time is 3.347060 seconds.
---------------- With sassy BSXFUN
Elapsed time is 0.966760 seconds.