Cell_in = {'a1','b1','b3','c3','c1','d3'};  % something like this

Cell_out = {'a1','b1','c1'; 
       'b3','c3','d3';...
       } 

And so on, how can this be done?

有帮助吗?

解决方案

Case 1: Consistent sizes

%%// Input (different from question for a better demo)
Cell_in = {'airplane1','bat1','ball3','cat3','coal1','doggie3'};

ids = cellfun(@(x) x(end), Cell_in,'uni',0) 
[~,ind] = sort(ids)
Cell_out = reshape(Cell_in(ind),[],numel(unique(ids)))' %%// Output

Output

Cell_out = 

    'airplane1'    'bat1'    'coal1'  
    'ball3'        'cat3'    'doggie3'

Case 2: Inconsistent sizes

Cell_in = {'airplane1','bat1','ball3','cat3','coal1','doggie3','cat2','ball2'};

ids = cellfun(@(x) x(end), Cell_in,'uni',0)
unique_ids_num = cellfun(@str2num,unique(ids))
ids_num = cellfun(@str2num,ids)

counts = histc(ids_num,sort(unique_ids_num))

Cell_out = cell(numel(unique_ids_num),max(counts));
for k =1:numel(counts) %%// Maybe accumarray can work here
    Cell_out(k,1:counts(k)) = Cell_in(ids_num==unique_ids_num(k));
end

Output

Cell_out = 

    'airplane1'    'bat1'     'coal1'  
    'cat2'         'ball2'           []
    'ball3'        'cat3'     'doggie3'

其他提示

Using regexp, as suggested by kyamagu, followed by accumarray to do the grouping:

[~,~,ic] = unique(cell2mat(regexp(Cell_in(:), '\d+$', 'match', 'once')));
[ic,inds] = sort(ic); % to ensure stable ordering of output
co = accumarray(ic,inds,[],@(x){Cell_in(x)});
Cell_out = vertcat(co{:});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top