Effacer les filtres
Effacer les filtres

cell array sort

1 vue (au cours des 30 derniers jours)
Yingke
Yingke le 25 Juin 2012
Dear All
I have A = {[1 2]; [2 2]; [2 1 3]; [1 1 3] }, a cell array contains several vectors with various length.
Input :
[1 2]
[2 2]
[2 1 3]
[1 1 3]
and I want to sort this cell array according to ascent order of each element, and regardless the length.
What I expect to have is
[1 1 3]
[1 2]
[2 1 3]
[2 2].
What I use is convert vector to string, and then sort the strings.
=====
% each number should have the same length in string.
ind = cellfun(@(x) num2str(x,'%05.f,'), A, 'UniformOutput',false);
=====
However, num2str is expensive. Do you have any other good idea to do this? Thanks!!!

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 25 Juin 2012
[id,id] = sortrows(cell2mat(cellfun(@(x)x(1:2),A,'un',0)));
out = A(id);
other
m = cellfun(@numel,A);
k = arrayfun(@(x,y)[x{1} zeros(1,max(m)-y)],A,m,'un',0);
[id,id] = sortrows(cat(1,k{:}));
out = A(id);
other 2
[id,id] = sort(cellfun(@num2str,A,'un',0));
out = A(id);
  1 commentaire
Yingke
Yingke le 25 Juin 2012
Thanks for your quick reply.
However, the lengths are various. Cell2mat may not applicable.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Cell Arrays dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by