Sum across columns with shift

4 visualizaciones (últimos 30 días)
Andrea Console
Andrea Console el 20 de Feb. de 2020
Comentada: andrea console el 25 de Feb. de 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?

Respuesta aceptada

dpb
dpb el 20 de Feb. de 2020
Editada: dpb el 22 de Feb. de 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 comentarios
Andrea Console
Andrea Console el 20 de Feb. de 2020
This is very smart, thank you!
andrea console
andrea console el 25 de Feb. de 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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by