general code for sorting inside cell
1 次查看(过去 30 天)
显示 更早的评论
ref=69;
A={[1,2,3,12],[19,34,37,15,33,35,36],[19,20,21,22,23,5,8,11,13,15,17],[37,38,65,40,42,49,66],[5,11,3,12],[69,19,21,22,23],[69,70,75]};
amount=[];
ref_include_index = cellfun(@(v)any(ismember(v,ref)),A);
ref_include_array = A(ref_include_index); % find array that include ref
amount=[ref_include_array{:},amount];
amount=unique(amount);
idv = cellfun(@(v)any(ismember(v,amount)),A);
idvv=A(idv&~ref_include_index);
amount=[idvv{:},amount];
amount=unique(amount);
idr = cellfun(@(v)any(ismember(v,amount)),A);
idrr=A(idr&~idv&~ref_include_index);
amount=[idrr{:},amount];
amount=unique(amount);
idm = cellfun(@(v)any(ismember(v,amount)),A);
idmm=A(idm&~idr&~idv&~ref_include_index);
amount=[idmm{:},amount];
amount=unique(amount);
result=[ref_include_array,idvv,idrr,idmm];
this code sorting A according to ref. if size of A is changing I have to copy and paste this line
idm = cellfun(@(v)any(ismember(v,amount)),A);
idmm=A(idm&~idr&~idv&~ref_include_index);
amount=[idmm{:},amount];
amount=unique(amount);
Is there any way to write better code for this?
2 个评论
采纳的回答
Jan
2019-3-7
编辑:Jan
2019-3-7
ref = 69;
A = {[1,2,3,12],[19,34,37,15,33,35,36],[19,20,21,22,23,5,8,11,13,15,17], ...
[37,38,65,40,42,49,66],[5,11,3,12],[69,19,21,22,23],[69,70,75]};
Result = {};
while ~isempty(A) % As long as A is not empty:
% Find vectors, which contain any element of ref:
match = cellfun(@(a) any(ismember(a, ref)), A);
% Attach found vectors to the output:
Result = cat(2, Result, A(match));
% Find new reference vector:
ref = unique(cat(2, A{match}));
% Crop matched vectors from A:
A = A(~match);
end
3 个评论
Jan
2019-3-8
编辑:Jan
2019-3-8
Why not "sorting" the arrays before the processing?
A = {[1,2,3,12],[19,34,37,15,33,35,36],[19,20,21,22,23,5,8,11,13,15,17], ...
[37,38,65,40,42,49,66],[5,11,3,12],[69,19,21,22,23],[69,70,75],[17,31,32,113],[41,69]};
index_base={[1],[1],[1],[4],[4],[1],[1],[2],[2]};
for iA = 1:numel(A)
if index_base{iA} ~= 1
v = A{iA};
m = (1:numel(v)) == index_base{iA};
A{iA} = [v(m), v(~m)];
end
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!