# One-liner to sort STRUCT in MATLAB?

Seeking a one-liner MATLAB function / command to sort by date the output of:

``````filenames = dir(filenameSubstring);  % retruns struct
``````

sortrows() is for matrices and seems to rely on the sorting column to be a number.

Seeking to avoid re-inventing the wheel and using MATLAB's stock capability. If a one-liner is not possible, then concise solutions are appreciated.

# UPDATE

Two-Liner per first comment in Mathworks blog:

``````%% Sort the struct by file save date
[tmp ind]=sort({filenames.date});
filenames=filenames(ind);
``````

## 1 Answer

Making a solution work is the first step. The solution in your post works only if all dates are from the same month and year.

Example:

If you have these dates:

``````'18-May-2017 01:01:36'
'18-Jun-2018 22:58:50'
'19-Jun-2018 01:52:32'
``````

your code arranges them as:

``````'18-Jun-2018 22:58:50'
'18-May-2017 01:01:36'
'19-Jun-2018 01:52:32'
``````

which is clearly wrong.

Your code can be fixed using `datetime` (introduced in R2014b) as follows:

``````[~, ind] = sort(datetime({filenames.date}));
filenames = filenames(ind);
``````

One-liners are overrated. Any approach to make it one-liner is very likely to be worse than the above elegant approach. If you just want to write it in one line then write it in one line as:

``````[~, ind] = sort(datetime({filenames.date}));  filenames = filenames(ind);
``````

or create a function that does that and call that function i.e.

``````function filenames = sortbydate(filenames)
[~, ind] = sort(datetime({filenames.date}));
filenames = filenames(ind);
end
``````

and call this function with:

``````filenames = sortbydate(filenames);
``````
• Good observation. – gatorback Jun 19 '18 at 20:46