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

Group cell-array row by an ID in another row

我有这个单元阵列:

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

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

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

一旦你有了它,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

我用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.'];