How can I sort the elements of a cell?

99封情书 提交于 2019-12-01 17:56:16

Your loop is slow because B is growing inside it; you should preallocate memory for B and it should run significantly faster. To do this, insert the following line before the for loop:

B = zeros(nrows, 1);

You can further shorten your loop like so:

B = zeros(size(A,1), 1);
for i = 1:size(A, 1)
    B(i, 1) = A{i}(1);
end
[Y, I] = sort(B);
Asorted = A(I);

EDIT

I decided to compare this solution with a shorter solution that employs cellfun (which I formerly proposed):

A = {[1; 2; 3], [4; 2], [3; 2; 5; 4; 6], [10; 2; 5; 7]};

% # Solution with a for loop
tic
for jj = 1:1e3
    B = zeros(size(A,1), 1);
    for i = 1:size(A, 1)
        B(i, 1) = A{i}(1);
    end
    [Y, I] = sort(B);
    Asorted = A(I);
end
toc

% # Solution with cellfun
tic
for jj = 1:1e3
    [Y, I] = sort( cellfun( @(x) x(1), A ) );
    Asorted = A(I);
end
toc

The results are:

Elapsed time is 0.028761 seconds.
Elapsed time is 0.253888 seconds.

The loop runs by an order of magnitude faster than cellfun! This difference can be extremely noticeable for large arrays, so I recommend using a for loop in this problem.

You can use cellfun

[~, I] = sort( cellfun( @(x) x(1), A ) );
Asorted = A(I);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!