How to sum up a matrix with upper diagonal direction without for-loop condition

1 次查看(过去 30 天)
How can I make the following 2-D matrix into 1D matrix by summing up the 2-D matrix with upper diagonal direction with no use of for-loop condition?
A= [ 1 2 3 4 5 6 7 8 9; 2 3 4 5 6 7 8 9 10; 3 4 5 6 7 8 9 10 11;]
B = [1 4 9 12 15 18 21 24 27 20 11];
More detail, B = [1 (2+2) (3+3+3) (4+4+4) (5+5+5) (6+6+6) (7+7+7) (8+8+8) (9+9+9) (10+10) (11)];

回答(2 个)

Azzi Abdelmalek
Azzi Abdelmalek 2014-1-11
编辑:Azzi Abdelmalek 2014-1-11
A= [ 1 2 3 4 5 6 7 8 9; 2 3 4 5 6 7 8 9 10; 3 4 5 6 7 8 9 10 11];
[n,m]=size(A);
A(:,end+1:end+n-1)=0;
B=sum(cell2mat(arrayfun(@(x) circshift(A(x,:),[0 x-1]),(1:n)','un',0')))

Azzi Abdelmalek
Azzi Abdelmalek 2014-1-11
This one should be faster
A= [ 1 2 3 4 5 6 7 8 9; 2 3 4 5 6 7 8 9 10; 3 4 5 6 7 8 9 10 11]%
[n,m]=size(A);
A(:,end+1:end+n-1)=0;
p=n+m-1;
id2=rem(bsxfun(@plus,p-(0:n-1)',1:p),p);
id2(~id2)=p;
id1=repmat((1:n)',1,p);
ii=sub2ind(size(A),id1,id2);
B=sum(A(ii))

类别

Help CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by