Sum across columns with shift

4 次查看(过去 30 天)
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?

采纳的回答

dpb
dpb 2020-2-20
编辑:dpb 2020-2-22
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 个评论
Andrea Console
Andrea Console 2020-2-20
This is very smart, thank you!
andrea console
andrea console 2020-2-25
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by