Sum across columns with shift

3 visualizzazioni (ultimi 30 giorni)
Andrea Console
Andrea Console il 20 Feb 2020
Commentato: andrea console il 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?

Risposta accettata

dpb
dpb il 20 Feb 2020
Modificato: dpb il 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 Commenti
Andrea Console
Andrea Console il 20 Feb 2020
This is very smart, thank you!
andrea console
andrea console il 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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by