移动二维元胞数组中的空元胞

moving empty cells in 2D cell array

是否可以将空条目移动到二维元胞数组的末尾?例如。如果单元格 (2,2) 是 [],则单元格 (3,2) 将进入 (2,2) 的位置,(4,2) 进入 (3,2) 等,并且空值将例如附加在最后一行。

C = {1 []; [] 4; 'aa' []}; %// example cell array
e = cellfun('isempty', C); %// this indicates for each cell if it's empty or not
[~, r] = sort(e, 1); %// sorting of each col to move empty cells to the end
[m, n] = size(C);
C = C(bsxfun(@plus, r, (0:m:m*(n-1)))); %// apply sorting to each col, using linear indexing

在这个例子中,C最初是

C = 
    [ 1]     []
      []    [4]
    'aa'     []

变成

C = 
    [ 1]    [4]
    'aa'     []
      []     []

一些备注:

  • 这是有效的,因为 sort 稳定的 :它保留原始顺序以防平局。请注意,e 仅包含零和一。
  • Linear indexing is done efficiently with bsxfun. (repmat and sub2ind 可以代替。)