Clear Filters
Clear Filters

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

1 view (last 30 days)
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)];

Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 11 Jan 2014
Edited: Azzi Abdelmalek on 11 Jan 2014
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 on 11 Jan 2014
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))

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!