如何组合数字并在不同列中添加数字

时间:2015-02-25 13:39:45

标签: matlab matrix

这是我以前的问题(onetwo)的延续,这是我的真正问题 我有一系列数据:

a   b   c   d
0   1   2   5
0   1   7   1
0   0   5   5
0   0   0   1
0   1   0   2

正如你所看到的,我希望abc能够组合在一个列中,就像这样:

abc    d
012    5
017    1
005    5
000    1
010    2 

所以我现在有2列abc和d

接下来我想计算d的重复值,将其加起来并组合相应的abc,见下文

abc        d
012,005    10
017,010    2
010        5

所以你可以看到,012和005结合起因为它们具有相同的d值,并且它们的d加起来因此它变为10,所以我怎么能这样做?这是我真正的问题,请帮忙谢谢。

1 个答案:

答案 0 :(得分:4)

A = [...
0   1   2   5;
0   1   7   1;
0   0   5   5;
0   0   0   1;
0   1   0   2 ]

%// column for identification
subs = A(:,4);
%// get order for sorting output
order = unique(subs,'stable')

%// get strings from numbers
abc = cellstr(reshape(sprintf('%i',A(:,1:3)),size(A(:,1:3))))

%// gather abc
groups = accumarray(subs,1:numel(subs),[],@(x) {abc(x)})

%// sum counts
counts = accumarray(subs,subs,[],@sum)

%// output
out = [groups num2cell(counts)]

%// reorder output
out = out(order,:)

%// filter output
out(find(~counts(order)),:) = []

out = 

    {2x1 cell}    [10]
    {2x1 cell}    [ 2]
    {1x1 cell}    [ 2]

例如

out{1,1} = 

'005'
'012'

如您所见out{1,1}仍未按正确顺序排列。原因是accumarray is not stable。要解决此问题,请使用链接中提供的函数accumarrayStable

function A = accumarrayStable(subs, val, varargin)
[subs(:,end:-1:1), I] = sortrows(subs(:,end:-1:1));
A = accumarray(subs, val(I), varargin{:});
end

你最终会得到:

out{1,1} =

    '012'
    '005'