natsortfiles is not working for .png files

9 views (last 30 days)
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?

Accepted Answer

Image Analyst
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
  3 Comments
Anu
Anu on 5 Jan 2022
Thanks for your great suggestion. I am very new to Matlab but this forum is actually helping me to learn a lot of things. I completely agree with you, it's great to have natsortfiles() that Stephen had created. Thanks once again.

Sign in to comment.

More Answers (1)

Stephen23
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
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.

Sign in to comment.

Categories

Find more on Search Path in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!