我有一个类似A的矩阵,希望计算出每条对角线上元素的和并显示在向量Y中。
A=[1 2 3; 4 5 6; 7 8 9]
Y=[3 8 15 12 7]
我了解这段代码。
[sum(diag(y,2)),sum(diag(y,1)),sum(diag(y,0)),sum(diag (y,-1)),sum(diag (y,-2))]
但我想将其编写为函数。
[r ,c]=size(A);
idx=bsxfun(@plus,(r:-1:1)',0:c-1);
s=flipud(accumarray(idx(:),A(:)));
与其他答案中提出的 spdiags
相比,这种方法在 Octave 中表现得更好。 基准测试:
A = rand(1000);
disp('---------bsxfun+accumarray----------')
tic
[r ,c]=size(A);
idx=bsxfun(@plus,(r:-1:1)',0:c-1);
s=flipud(accumarray(idx(:),A(:)));
toc
disp('---------spdiags----------')
tic
dsum = fliplr(sum(spdiags(A)));
toc
结果:
---------bsxfun+accumarray----------
Elapsed time is 0.0114651 seconds.
---------spdiags----------
Elapsed time is 8.62041 seconds.
accumarray
之前使用toeplitz
生成指数:[r, c] = size(A);
index = toeplitz(c:(r+c-1), c:-1:1);
Y = accumarray(index(:), A(:)).';
bsxfun
的使用并直接使用(r:-1:1)' + (0:c-1)
:)! - TwistedSimbsxfun
而不是隐式扩展! :) - rahnema1