Search code examples
stringmatlabsortingstructdir

Matlab: sorting strings on size in a struct field


This problem is bugging me and the solution is probably obvious but i cant find it.

I have a bunch of data files which i want to load:

ex_file-1.txt, ex_file-2.txt, ..., ex_file-10.txt

To get their filenames i use:

files = dir('ex_file-*.txt');

This returns a struct with fields name, type, etc. The field name returns:

ex_file-1.txt, ex_file-10.txt, ex_file-2.txt, ..., ex_file-9.txt

I would like to sort this such that ex_file-10.txt is the last file rather than the second.

I have attempted to concatenate, convert to cells and sort but none seem to give what i need. I know that the most obvious solution would be to rename all file names so all strings have the same length but i'd prefer not to do that.


Solution

  • Here is a alternative which does not require any details about the file name. Primary sorting rule shortest first, secondary lexicographic:

    %secondary sorting
    list=sort(list);
    %primary sorting by length
    [a,b]=sort(cellfun(@numel,list)):
    list=list(b);