Summing few sequences in a vector
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
George Tsintsadze
le 20 Déc 2016
Commenté : Walter Roberson
le 20 Déc 2016
How can I sum few sequences in a vector? For example, if I have the vector:
A = [1 1 0 4 1 1 0 2 1 1 1]
I want to get the vector:
B = [2 6 5]
Which is the sum of sequences separated by zero.
Of curse I wand to do it without any for/while loops.
Thank you.
0 commentaires
Réponse acceptée
Walter Roberson
le 20 Déc 2016
t1 = cumsum(A);
B = diff([0,t1(A==0),B(end)]);
Plus de réponses (2)
KSSV
le 20 Déc 2016
Modifié(e) : KSSV
le 20 Déc 2016
A = [1 1 0 4 1 1 0 2 1 1 1] ;
ne0 = find(A~=0); % Nonzero Elements
i0 = unique([ne0(1) ne0(diff([0 ne0])>1)]); % Segment Start Indices
i1 = ne0([find(diff([0 ne0])>1)-1 length(ne0)]); % Segment End Indices
for k1 = 1:length(i0)
section{k1} = A(i0(k1):i1(k1));
end
iwant = cellfun(@sum,section)
José-Luis
le 20 Déc 2016
Not particularly efficient but fulfilling the eternal quest for one liners:
result = cellfun(@(x) sum(x((x - '0') > 0 & (x - '0') <= 9 ) - '0'), strsplit(num2str(A),'0'))
2 commentaires
José-Luis
le 20 Déc 2016
Because
strsplit(num2str(A),'0')
returns a cell array of character arrays and I wanted to perform the comparisons on numbers. It's just a way of transitioning from characters to numbers. Otherwise some unnecessary blank characters would have been included in the computation.
Please accept the answer that best solves your problem.
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!