Filter löschen
Filter löschen

cell array sort

1 Ansicht (letzte 30 Tage)
Yingke
Yingke am 25 Jun. 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!!!

Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 25 Jun. 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 Kommentar
Yingke
Yingke am 25 Jun. 2012
Thanks for your quick reply.
However, the lengths are various. Cell2mat may not applicable.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Cell Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by