natsortfiles is not working for .png files
9 views (last 30 days)
Show older comments
I have downloaded the FEX from https://uk.mathworks.com/matlabcentral/fileexchange/47434-natural-order-filename-sort
To sort some of my png files in a folder. I have unzipped the natsortfiles folder and kept it in the current directory. While this is perfectly working for sorting the mat files in a folder, it is unrecognized when I am trying to use for image files (in png format).
I have used following code:
S = dir('raw*.png'); % get list of data files in directory that named with raw
S = natsortfiles(S); % sorts file names into natural order
N = length(S) ;
The error is "Unrecognized function or variable 'natsortfiles'."
Any suggestion/help, please?
0 Comments
Accepted Answer
Image Analyst
on 4 Jan 2022
Edited: Image Analyst
on 4 Jan 2022
S is a structure. First get the filenames, then call natsortfile:
S = dir('raw*.png'); % Get list of data files in directory that named with raw into a structure.
allFileNames = {S.name}; % Extract only the filenames from the structure.
numberOfFiles = length(allFileNames);
if numberOfFiles > 1
allFileNames = natsortfiles(allFileNames); % sorts file names into natural order
end
More Answers (1)
Stephen23
on 21 May 2023
Edited: Stephen23
on 21 May 2023
This page turns up relatively high on some Google searches, so I might as well make some corrections:
"S is a structure. First get the filenames, then call natsortfile:" is not required: NATSORTFILES is written to accept the structure returned by DIR directly. This is shown in both the Mfile help and the HTML documentation.
Nor is it really required to check the length and only call NATSORTFILES if there are multiple filenames: although internally NATSORTFILES does not have special case handling for zero or one filename**, it does handle them perfectly without any error.
So the simpler, recommended code (as shown in the NATSORTFILES help and documentation) is simply like this:
S = dir('raw*.png');
S = natsortfiles(S);
... which is exactly what the OP was using.
** I considered this but it a) just added complexity and b) gives inconsistent outputs, e.g. generating the 3rd output requires parsing the filenames anyway, at which point the actual sort is a only a minor additional runtime consumer.
3 Comments
Image Analyst
on 21 May 2023
It wouldn't be the first time someone said they did it one way and actually did it a different way.

See Also
Categories
Find more on Search Path 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!