Summing the elements of cell arrays for only certain values

2 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Jos (10584)
Jos (10584) il 3 Apr 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)]

Più risposte (1)

Azzi Abdelmalek
Azzi Abdelmalek il 2 Apr 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)]

Categorie

Scopri di più su Data Types in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by