Sorting the name field in dir command

157 visualizaciones (últimos 30 días)
Raúl
Raúl el 14 de Mzo. de 2013
Editada: Stephen23 el 18 de Abr. de 2021
Hi all,
I have a problem when I'm trying to get the content of a folder. It gets the name of the files but not in order. For example, the files starts with X- where the X is a number from 1 to 320. My code gets the name's file in the order 1, 10, 100, etc... and I need it in order 1,2,3,4...320
This is my code
myFolder = 'C:\Users\U95511\Dropbox\UPF\Roberto Verino\Advantrack\Test15-130313\P12\A3\Results';
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
filePattern = fullfile(myFolder, '*.xls');
xlsFiles = dir(filePattern);
I need to order the struct xlsFiles.
I tried with W=sort(xlsFiles.name) but it creates an array instead of another struct ordered.
Thanks for the help.
BR,
Raúl.

Respuestas (4)

Jonathan Sullivan
Jonathan Sullivan el 14 de Mzo. de 2013
Editada: Jonathan Sullivan el 14 de Mzo. de 2013
[~,ind]=sort({xlsFiles.name});
W = xlsFiles(ind);
  2 comentarios
Raúl
Raúl el 14 de Mzo. de 2013
Thanks Jonathan,
But it continues unsorted...
Andre Guerra
Andre Guerra el 16 de Nov. de 2016
That did the trick for me! Thanks a bunch!

Iniciar sesión para comentar.


Azzi Abdelmalek
Azzi Abdelmalek el 14 de Mzo. de 2013
f= dir(filePattern);
xlsfiles={f.name}
xlsfiles=sort(xlsfiles)
  2 comentarios
Raúl
Raúl el 14 de Mzo. de 2013
Thanks Azzi,
It also creates an array instead of a struct.
Azzi Abdelmalek
Azzi Abdelmalek el 14 de Mzo. de 2013
Editada: Azzi Abdelmalek el 14 de Mzo. de 2013
yourfolder= dir(filePattern);
xlsfiles={yourfolder.name}
[~,idx]=sort(xlsfiles)
new_folder=yourfolder(idx)

Iniciar sesión para comentar.


Stephen23
Stephen23 el 18 de Abr. de 2021
Editada: Stephen23 el 18 de Abr. de 2021
You could download my FEX submission natsortfiles:
>> S = dir('*.txt');
>> S.name
ans =
'1.txt'
ans =
'10.txt'
ans =
'2.txt'
>> S = natsortfiles(S); % alphanumeric sort by filename
>> S.name
ans =
'1.txt'
ans =
'2.txt'
ans =
'10.txt'

Dan
Dan el 16 de Mzo. de 2021
Most of the time you don't need to actually sort the names. You can use the index to control the order in which a loop will access the names. This code works for me on version 2020b.
filePattern = '*.*';
files = dir(filePattern);
[~,idx] = sort(string({files.name}),2,'ascend');
for fileLoop=idx
% do something with files like print the names in order
fprintf('File: %d, %s', fileLoop, files(fileLoop).name)
end

Categorías

Más información sobre File Operations en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by