importing a series of text file and save them into a array

1 view (last 30 days)
I have 54 text files sequatially named as follow.
2021.01.19_KBSI_CCM_Sa 3(Alq3-TAPC)_P_Bi3_200um_Ar_z-ROI#1.TXT
...
2021.01.19_KBSI_CCM_Sa 3(Alq3-TAPC)_P_Bi3_200um_Ar_z-ROI#54.TXT
I want to import 50 text files and save the files into a array such as "Alq3_TAPC{1} .... Alq3_TAPC{54}" . Can you let me know easier way of doing it? Thanks.
  1 Comment
Jan
Jan on 29 Jun 2022
What das "naming a text file" mean? Do you want to modifiy the file name? If so, what is the reason to import them before? Please edit the question and elaborate the details.

Sign in to comment.

Answers (1)

Prateekshya
Prateekshya on 6 Sep 2023
Hi Sunghwan,
As per my understanding you are trying to read a set of files following a specific naming convention. I assume that the files contain strings which need to be stored in "Alq3_TAPC" array sequentially. You can try the following code for the same.
fileCount = 54; % Total number of files
Alq3_TAPC = cell(1,fileCount); % Cell array to store the contents of the files
for count = 1 : fileCount % For each file
fileID = fopen(sprintf("2021.01.19_KBSI_CCM_Sa 3(Alq3-TAPC)_P_Bi3_200um_Ar_z-ROI#%d.txt",count), ...
"r"); % Generate the file name and open it in read mode
formatSpecifier = '%s';
Alq3_TAPC{count} = fscanf(fileID,formatSpecifier); % Read the content and store in the corresponding index
end
For data types other than string you can modify the "formatSpecifier" variable. For more information please go through: https://in.mathworks.com/help/matlab/ref/fscanf.html
I hope this helps!

Community Treasure Hunt

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

Start Hunting!