Sum variable size chunks in array
Mostra commenti meno recenti
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!
Risposta accettata
Più risposte (1)
Fangjun Jiang
il 20 Mar 2019
Modificato: Fangjun Jiang
il 20 Mar 2019
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 Commento
Tudorel Afilipoae
il 27 Mar 2019
Categorie
Scopri di più su Logical in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!