One-liner to sort STRUCT in MATLAB?

1

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);

gatorback

Posted 2018-06-11T21:25:34.873

Reputation: 741

Answers

2

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);

Sardar_Usama

Posted 2018-06-11T21:25:34.873

Reputation: 1 673

1Good observation. – gatorback – 2018-06-19T20:46:42.687