下面是迄今为止提到的所有方法的比较,以及我能想到的一些其他变化。这是使用 TIMEIT 函数在 64 位 R2013a 上测试的。
function [t,v] = testAntiDiag()
% data and functions
A = magic(5000);
f = {
@() func0(A) ;
@() func1(A) ;
@() func2(A) ;
@() func3(A) ;
@() func4(A) ;
@() func5(A) ;
@() func6(A) ;
@() func7(A) ;
};
% timeit and check results
t = cellfun(@timeit, f, 'UniformOutput',true);
v = cellfun(@feval, f, 'UniformOutput',false);
assert( isequal(v{:}) )
end
function d = func0(A)
d = diag(A(end:-1:1,:));
end
function d = func1(A)
d = diag(flipud(A));
end
function d = func2(A)
d = flipud(diag(fliplr(A)));
end
function d = func3(A)
d = diag(rot90(A,3));
end
function d = func4(A)
n = size(A,1);
d = A(n:n-1:end-1).';
end
function d = func5(A)
n = size(A,1);
d = A(cumsum(n + [0,repmat(-1,1,n-1)])).';
end
function d = func6(A)
n = size(A,1);
d = A(sub2ind([n n], n:-1:1, 1:n)).';
end
function d = func7(A)
n = size(A,1);
d = zeros(n,1);
for i=1:n
d(i) = A(n-i+1,i);
end
end
时间安排(按照上面定义的相同顺序):
>> testAntiDiag
ans =
0.078635867152801
0.077895631970976 % @AlexR.
0.080368641824528
0.195832501156751
0.000074983294297 % @thefourtheye
0.000143019460665 % @woodchips
0.000174679680437
0.000152488508547 % for-loop
对我来说最令人惊讶的结果是最后一个。显然,JIT 编译在这种简单的 for 循环上非常有效。