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

19 ビュー (過去 30 日間)
HYUNCHUL
HYUNCHUL 2014 年 1 月 11 日
回答済み: Azzi Abdelmalek 2014 年 1 月 11 日
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 Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by