Sum across columns with shift

조회 수: 4 (최근 30일)
Andrea Console
Andrea Console 2020년 2월 20일
댓글: andrea console 2020년 2월 25일
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