按另一行中的ID对单元格数组进行分组

时间:2015-07-09 12:40:49

标签: matlab matrix grouping cell-array

我有这个单元格数组:

QueueArr = ...
{   [1]    [5]    [1]    [2]    [1]    [ 1]    [ 5]    [ 1]    [ 2] ;  
    [6]    [8]    [7]    [9]    [5]    [10]    [18]    [17]    [19] }

现在我想根据第一行分组第二行。我的结果单元格数组应如下所示:

loopCell = ...
{    [          1]    [          2]    [          5] ;
     [6 7 5 10 17]    [       9 19]    [       8 18] }

我用这段代码解决了这个问题:

%// convert from cell to a matrix
loopMatrix = cell2mat(QueueArr);
%// get the unique elements from the first row
loopMatrixUnique = unique(loopMatrix(1,:));
%// create the result cell
loopCell = cell(2,size(loopMatrixUnique,2));
%// iterate through the unique indexes
for i = 1:size(loopMatrixUnique,2)
    %// saving the first row
    loopCell{1,i} = loopMatrixUnique(i);
    %// calculating the grouped elements
    loopCell{2,i} = loopMatrix(2,loopMatrix(1,:) == loopMatrixUnique(i));
end

我现在的问题是我的问题是否有更简单或更理想的解决方案。

2 个答案:

答案 0 :(得分:1)

正如评论中所说,unique的第3项输出对您的案例非常有用。

完成后,cellfun也可用于快速重建单元阵列:

b = cell2mat(QueueArr(2,:)) ; %// convert bottom line to array for convenience

[C,~,ic]= unique( cell2mat(QueueArr(1,:)) ) ;

R = [ num2cell(C) ; ...                                             %// top row
      cellfun( @(x) b(ic==x) , num2cell(1:length(C)) , 'uni',0)  ]  %// bottom row

答案 1 :(得分:1)

我自己用accumarray解决了这个问题。 请提示@Dan提示。

%// save the second row
sections = [QueueArr{2,:}];

%// get unique chapters and subs
[chapters, ~, subs] = unique([QueueArr{1,:}]);

%// create the grouped cell-array 
groups = accumarray(subs, sections, [], @(x) {x});

%// create the result cell-array
loopCell = [num2cell(chatpers); groups.'];