Summing the elements of cell arrays for only certain values

2 vues (au cours des 30 derniers jours)
Daniel
Daniel le 2 Avr 2014
Does anyone know an efficient way to sum up the last value in a unique instances of a cell array of strings?
For instance
A = {'a', 'b', 'c', 2
'a', 'b', 'd', 3
'b', 'c', 'd', 7
'a', 'b', 'd', 10};
the answer that I would return would be every unique combination so I would return a cell array with three unique strings, with values of 2, 7, and 13.

Réponse acceptée

Jos (10584)
Jos (10584) le 3 Avr 2014
[~,~,j] = unique(A(:,1:3)) ;
[~,x,k] = unique(reshape(j,[],3),'rows')
S = accumarray(k,[A{:,4}])
out = [A(x,1:3) num2cell(S)]

Plus de réponses (1)

Azzi Abdelmalek
Azzi Abdelmalek le 2 Avr 2014
A = {'a', 'b', 'c', 2
'a', 'b', 'd', 3
'b', 'c', 'd', 7
'a', 'b', 'd', 10}
c=A(:,1:3)
d=arrayfun(@(x) strjoin(c(x,:)),(1:size(c,1))','un',0)
[qq,idx,kk]=unique(d,'rows','stable')
f=accumarray(kk,cell2mat(A(:,4)))
out=[c(idx,:) num2cell(f)]

Catégories

En savoir plus sur Data Types dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by