How do I sort filenames containing text and numbers in numerical order in MATLAB?
Show older comments
I have a series of .png files in a folder whose names are the following;
(A)Test_Nom_BAUD1.png
(A)Test_Nom_BAUD7.png
(A)Test_Nom_BAUD8.png
(A)Test_Nom_BAUD10.png
(A)Test_Nom_BAUD11.png
In reading the MATLAB documentation, I understand the dir function sorts strings in ASCII dictionary order. And since the files I'm using have no leading zeros, this is a problem. This is exactly what I'm seeing when I use the dir function:
A = dir('*.png');
(A)Test_Nom_BAUD1.png
(A)Test_Nom_BAUD10.png
(A)Test_Nom_BAUD11png
(A)Test_Nom_BAUD7.png
(A)Test_Nom_BAUD8.png
But what I need is this;
A = dir('*.png');
(A)Test_Nom_BAUD1.png
(A)Test_Nom_BAUD7.png
(A)Test_Nom_BAUD8.png
(A)Test_Nom_BAUD10.png
(A)Test_Nom_BAUD11.png
I know this can be done if the filenames contain only numbers.
But is it possible to sort these filenames (in numerical order) using existing text manipulation and sorting routines in MATLAB? If so, how?
1 Comment
"If so, how?"
S = dir('*.png');
S = natsortfiles(S); % alphanumeric sort by filename
Accepted Answer
More Answers (2)
KSSV
on 10 Oct 2017
1 vote
2 Comments
Brad
on 10 Oct 2017
Jan
on 10 Oct 2017
Really? But it is on the same server as the forum. Perhaps it works if you insert your country code:
https://mathworks.com/matlabcentral/fileexchange/10959-sort-nat--natural-order-sort (For the US site, or "https://de." for Germany etc.
Image Analyst
on 10 Oct 2017
1 vote
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!