Sum across columns with shift

4 views (last 30 days)
Andrea Console
Andrea Console on 20 Feb 2020
Commented: andrea console on 25 Feb 2020
I have a matrix a, let say 20 rows and 10 columns. I want to obtain an array b where b(1)=a(1,1) b(2)=a(1,2)+a(2,1) b(3)=a(1,3)+a(2,2)+a(3,1) ... b(20+10-1)=a(20,10) In practice, every row of the a matrix is shifted right by one column with respect to the row above and then the elements of each column of the resulting (larger) matrix are summed. Is it possible to obtain this without loops and without building the big shifted matrix?

Accepted Answer

dpb
dpb on 20 Feb 2020
Edited: dpb on 22 Feb 2020
May be some other more clever indexing, but the "deadahead" thing that comes to mind if I understand the desire
>> a=1:18;a=reshape(a,6,[]) % sample smaller dataset for illustration...
a =
1 7 13
2 8 14
3 9 15
4 10 16
5 11 17
6 12 18
The engine
[r,c]=size(a); % get the array dimensions
b=arrayfun(@(i) sum(diag(flipud(a),i)),-(r-1):c-1); % sum diagonals in desired sequence
Result
>> b
b =
1 9 24 27 30 33 29 18
>>
ADDENDUM:
Somewhat cleaner is to subtract earlier for the indexing cleanup...
[r,c]=size(a)-1; % array dimensions less one for 0-base count
b=arrayfun(@(i) sum(diag(flipud(a),i)),r:c); % sum diagonals in desired sequence
  2 Comments
Andrea Console
Andrea Console on 20 Feb 2020
This is very smart, thank you!
andrea console
andrea console on 25 Feb 2020
How hard do you think it could be to extend this answer to a three-dimensional case? I.e. sum of bidimensional matrices shifted across one of the axes

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays 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!