Sort cell array according to number of elements

A= [-0.054;-0.43;0.022] [-0.43;-0.18] [0.02;0.002;-0.202;-0.41]
Before applying cell2mat I want to reorder the array in ascending order according to the number of elements so NewA= [-0.43;-0.18] [-0.054;-0.43;0.022] [0.02;0.002;-0.202;-0.41]

 採用された回答

Andrew Newell
Andrew Newell 2011 年 4 月 6 日

2 投票

[~,I] = sort(cellfun(@length,A));
A = A(I);

4 件のコメント

Jan
Jan 2011 年 4 月 6 日
cellfun('length', A) is remarkably faster. cellfun(@length, A) uses mexCallMATLAB for each cell element, but the methods defined by a string are perfromend inside the Mex function.
Andrew Newell
Andrew Newell 2011 年 4 月 6 日
That's strange. In the documentation for cellfun in MATLAB 2010b, the string input is described as being available for backward compatibility - implying that it's not the preferred choice.
Jan
Jan 2011 年 4 月 6 日
Simply try it. Older Matlab version contained the C-source code of CELLFUN. It would be very helpful, if much more of these sweets is still available.
*But*: Perhaps a tricky prgorammer has found a method now to recognize @length such that no calls to external functions is necessary??
Andrew Newell
Andrew Newell 2011 年 4 月 6 日
You're right - the string call is about 20 times faster on my machine.

サインインしてコメントする。

その他の回答 (1 件)

Mariam Osmann
Mariam Osmann 2011 年 4 月 7 日

0 投票

Thanks

1 件のコメント

Sean de Wolski
Sean de Wolski 2011 年 4 月 7 日
Mariam, please accept Andrew's answer.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeShifting and Sorting Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by