Summing the elements of cell arrays for only certain values

2 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Jos (10584)
Jos (10584) el 3 de Abr. de 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)]

Más respuestas (1)

Azzi Abdelmalek
Azzi Abdelmalek el 2 de Abr. de 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)]

Categorías

Más información sobre Data Types en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by