필터 지우기
필터 지우기

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