Matlab 按另一行中的ID对单元格数组行进行分组
我得到了这个细胞阵列:Matlab 按另一行中的ID对单元格数组行进行分组,matlab,matrix,grouping,cell-array,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] [
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
我自己解决了。
谢谢@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.'];
您看过Accumaray的
了吗?它基本上是为这个任务而设计的。您会发现unique
的第三个输出有助于生成subs
输入。注意,您不需要cell2mat
,但可以使用与调用unique
中的部分使用的相同技术:…=唯一([QueueArr{1,:}])
。但我不确定哪一个更有效