cell array sort

1 次查看(过去 30 天)
Yingke
Yingke 2012-6-25
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!!!

采纳的回答

Andrei Bobrov
Andrei Bobrov 2012-6-25
[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 个评论
Yingke
Yingke 2012-6-25
Thanks for your quick reply.
However, the lengths are various. Cell2mat may not applicable.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by