How to read a file in series of files saved in a order.

6 views (last 30 days)
Hello everyone, I have saved files as IR_A_01_01.png, IR_B_01_02.png, IR_C_01_03.png, IR_D_01_04.png, IR_A_01_05.png......the string A-B-C-D-A is a cycle. The third digit 01 doesnt change but is important. The last digit increaments everytime. Everytime I run the program I have to read one image and in next run next image. So how I can read the files one after the other?
What I have come up with is to have a global variable which will be initialised to 01(global num) and increaments at end.And the string will be initialised with letter='A'which will change to 'B' at end. So the third digit wont change. So if I say picture='IR_%s_01_%d.png','letter','num'; I should be getting the file but I am unable. I have changed the directory before I did this. So i just need to program so that i can read them one after the other.
Would appreciate any input. Thank you all.
  3 Comments
Stephen23
Stephen23 on 7 Feb 2017
Edited: Stephen23 on 7 Feb 2017
@Pavan Basavaraj: read my comment again. The very first two words are: "use dir". Like this:
S = dir('*.png');
C = {S.name};
And then use the rest of my code.
I simply used the names you gave as an example to test my code with. To show that it works. So that I could test it. You just need to use dir (which I wrote at the start of my comment).
Also note that you may need to use fullfile if the files are not in the current directory. Do not use cd.

Sign in to comment.

Answers (1)

Shivam
Shivam on 30 Jul 2022
You can sort files by sorting modification date.
All you would need is:
D = '.'; % folder path
files = dir(fullfile(D,'*.dat'));
[~,idx] = sort([files.datenum]);
This idx contains the values from oldest files(idx(1)) to newest files(idx(end)). Use 'descend' as an option in sort() if you want to edit the newest first.
for k = 1:numel(idx)
F = fullfile(D,idx(k).name)
... import/process file F
end
  1 Comment
Walter Roberson
Walter Roberson on 30 Jul 2022
In my experience, modification date is quite unreliable to sort by.
For example if you use operating system calls to move files between directories on the same file system then the modification time is likely preserved. If you copy instead of move to the same file system, then it is operating system dependent whether the copies have the old modification date or the new one. If you copy or move between different file systems on the same computer, then there is a higher risk that the dates will be updated. If you are writing to a network file system then the modification date is quite likely to be updated, but it depends on whether you are using an enterprise grade network file system or a hack such as OneDrive

Sign in to comment.

Categories

Find more on File Operations 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!

Translated by