Matlab表上的汇总

时间:2018-10-29 15:51:25

标签: matlab aggregation

我在matlab中有下表,我想根据列 name

汇总此表
name      nums
'es'     '1,2,3'
'mo'     '4,3,1'
'al'     '2,3,1'
'es'     '40,2,8'
'es'     '1,2,5'
'mo'     '5,2,1'
'ta'     '9,4,2'
'al'     '2,6,1'
...

这是我想要的输出(数字应该是唯一的):

name     nums
'es'     '1,2,3,8,40,5'
'mo'     '4,3,1,5,2'
'al'     '2,3,1,6'
'ta'     '9,4,2'
...

这是我的代码,

n,m = size(T);
for i = 1:n
    if ~ismember(name,mynewtab)
         mynewtab.input(i).nums = mynewtab.input(i).nums + nums;
    else
         mynewtab.input(i).nums = mynewtab.input(i).nums + nums;
         mynewtab.input(i).name = name;
    end
end

但是此代码有一些错误。

1 个答案:

答案 0 :(得分:3)

“此代码有一些错误”不是一个很好的问题说明,您应该从一个事实开始,即+的定义不像您想象的字符数组那样。

使用strjoinunique的这段代码应该可以满足您的要求。...

uNames = unique(tbl.name);    % Get unique names
c = cell( numel(uNames), 2 ); % Set up output (we'll turn this into a table later)
for ii = 1:numel(uNames)
    c{ii,1} = uNames{ii}; % Assign the name to 1st column
    % Join all strings in the 'nums' column, with a comma between them, when the 
    % value in the names column is equal to uNames{ii}
    c{ii,2} = strjoin( tbl.nums( strcmp( tbl.name, uNames{ii} ) ).', ',' );
end

tblOut = cell2table( c, 'VariableNames', {'name','nums'} );

如果只希望字符串中包含唯一的元素,则必须使用strsplit来分割逗号,然后在调用unique之后将它们连接在一起...替换c{ii,2} = ...行如下:

vals = tbl.nums( strcmp( tbl.name, uNames{ii} ) ).';       % Get nums for this name
vals = cellfun( @(str)strsplit(str,','), vals, 'uni', 0 ); % Split all on ','
% Join the list of unique values back together. 
% Could use 'stable' argument of unique for order preservation.
c{ii,2} = strjoin( unique( [vals{:}] ), ',' ); 

注意:如果您将数字列表存储为实际数字数组而不是字符数组,这一切都将变得容易得多!