Changing the Reading of Files in a For Loop

Hello,
I recently found a thread where someone gave me a code to read through a file and compile them into a single .mat file, first thank you to that person.
clear
Folder='C:\Users\runsw\Desktop\Honors Thesis\CJ SVI GS';
myFiles = dir(fullfile(Folder,'*.met')); %gets all met files in struct
for k = 1:length(myFiles)
baseFileName = myFiles(k).name;
fullFileName = fullfile(Folder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
end
Output:
Now reading C:\Users\runsw\Desktop\Honors Thesis\CJ SVI GS\SVI024_0-0.5cm.MET
Now reading C:\Users\runsw\Desktop\Honors Thesis\CJ SVI GS\SVI024_0.5-1cm.MET
Now reading C:\Users\runsw\Desktop\Honors Thesis\CJ SVI GS\SVI024_1-1.5cm.MET
Now reading C:\Users\runsw\Desktop\Honors Thesis\CJ SVI GS\SVI024_1.5-2cm.MET
Now reading C:\Users\runsw\Desktop\Honors Thesis\CJ SVI GS\SVI024_10-10.5cm.MET
Now reading C:\Users\runsw\Desktop\Honors Thesis\CJ SVI GS\SVI024_10.5-11cm.MET
Now reading C:\Users\runsw\Desktop\Honors Thesis\CJ SVI GS\SVI024_100-100.5cm.MET
Now reading C:\Users\runsw\Desktop\Honors Thesis\CJ SVI GS\SVI024_100.5-101cm.MET
Now reading C:\Users\runsw\Desktop\Honors Thesis\CJ SVI GS\SVI024_101-101.5cm.MET
Now reading C:\Users\runsw\Desktop\Honors Thesis\CJ SVI GS\SVI024_101.5-102cm.MET
However the issue i have occuring is that the code is reading my files in an odd way. my files are labelled as SVI024_0-0.5cm, SVI024_0.5-1cm, etc., the only difference in these files is the numbers, increasing by 0.5. this code reads the files in a werid order. where ,for example, file 1.5-2cm is read, the next file to be read is the 10-10.5 file, is there a way to change the code to read the files in increasing order, rather than reading it as it does?

1 Comment

Hi, you could do it like this:
foldername = 'C:\Users\runsw\Desktop\Honors Thesis\CJ SVI GS'
filename = '\SVI024_'
a = 0
b = 0.5
for i = 1:length(myFiles)
complete_filename = strcat(foldername, filename, string(a), '-', string(b), 'cm.MET')
a = a+0.5;
b = b+0.5;
end
Hope this helps!

Sign in to comment.

 Accepted Answer

Jan
Jan on 20 Oct 2022
Edited: Jan on 21 Oct 2022
Folder='C:\Users\runsw\Desktop\Honors Thesis\CJ SVI GS';
List = dir(fullfile(Folder,'*.met')
Name = {List.name};
... Now sort the names using the suggested tools
[EDITED] Consider Stephen's following comment.

1 Comment

NATSORTFILES also operates on the structure returned by DIR, so you can simply do:
List = dir(fullfile(Folder,'*.met');
List = natsortfiles(List);

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Release

R2022a

Asked:

on 20 Oct 2022

Edited:

Jan
on 21 Oct 2022

Community Treasure Hunt

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

Start Hunting!