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]

 Akzeptierte Antwort

Andrew Newell
Andrew Newell am 6 Apr. 2011

2 Stimmen

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

4 Kommentare

Jan
Jan am 6 Apr. 2011
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 am 6 Apr. 2011
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 am 6 Apr. 2011
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 am 6 Apr. 2011
You're right - the string call is about 20 times faster on my machine.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Mariam Osmann
Mariam Osmann am 7 Apr. 2011

0 Stimmen

Thanks

Kategorien

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by