Hello,
I am looking for a vectorized way of summing variable size chunks in a matrix, for example I have some matrix
A = [1 2 3 4 5 6 7 8
3 4 2 2 8 4 2 9]
and I want to do a rowwise summation using some vector as a rule, for example
v = [2 3 3]
In this case the result would be a 2x3 where the first column would be the summation of the first 2 columns in A (according to v),
the second column would be the summation of the next 3 columns in A etc. I can think of various ways of doing this using loops
but I am wondering if there is a faster vectorized way of doing it ?
Thank you!

 채택된 답변

Stephen23
Stephen23 2019년 3월 27일
편집: Stephen23 2019년 3월 27일

1 개 추천

Avoiding duplicating the data in memory (i.e. avoid mat2cell) will probably be faster for larger matrices:
fun = @(c){sum(A(:,c),2)};
G = repelem(1:numel(V),V);
C = 1:numel(G);
Z = accumarray(G(:),C(:),[],fun);
Z = horzcat(Z{:});
If your matrix only has two (or a fixed, small number) of rows, then this is much faster:
G = repelem(1:numel(V),V);
Y = [accumarray(G(:),A(1,:).'),...
accumarray(G(:),A(2,:).')].';
Here are some timing tests (1e4 iterations):
Elapsed time is 9.600425 seconds. % single ACCUMARRAY call.
Elapsed time is 0.208772 seconds. % dual ACCUMARRAY call.
Elapsed time is 11.146120 seconds. % Fangjun Jiang's answer.

댓글 수: 3

Tudorel Afilipoae
Tudorel Afilipoae 2019년 3월 27일
Thank you so much, the accumarray function is exactly what I was looking for. This is so much faster !!
Stephen23
Stephen23 2019년 3월 27일
@Tudorel Afilipoae: you can show your appreciation by accepting my answer.
Tudorel Afilipoae
Tudorel Afilipoae 2019년 3월 27일
Sorry, I wasn't aware that I could do this after already having accepted another answer..
Anyaway, my pleasure and thanks again!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Fangjun Jiang
Fangjun Jiang 2019년 3월 20일
편집: Fangjun Jiang 2019년 3월 20일

0 개 추천

B=mat2cell(A,size(A,1),v);
C=cellfun(@(x) sum(x(:)),B)
or should be this
B=mat2cell(A,size(A,1),v);
C=cell2mat(cellfun(@(x) sum(x,2),B,'uni',0));

댓글 수: 1

Tudorel Afilipoae
Tudorel Afilipoae 2019년 3월 27일
Thank you very much for your answer, indeed this was the only way I could do it without using loops. Unfortunately, the use of the mat2cell function makes the speed of the entire process comparable with the one of a loop.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

태그

질문:

2019년 3월 20일

댓글:

2019년 3월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by