MATLAB: How to read file with name consist of number and string

fopenfullfileloopMATLABmultiple filetextscan

Hello I have a folder(name is Site) with lots of .dat file in it. (site1g.dat site2g.dat site3g.dat site4s.dat site5s.dat site6s.dat site7m.dat …). I want to read all the files and use their data to do some simulations.
pathToFolder = './Site';
files = dir( fullfile(pathToFolder,'*.dat') );
data = cell(numel(files),1);
index = 'g s m d o f a h i j'
for i=1:numel(files)
fid = fopen([pathToFolder '/site' num2str(i) 'index' '.dat'], 'rt');
H = textscan(fid, '%s', 21, 'Delimiter','\n');
C = textscan(fid, repmat('%f ',1,8), 'Delimiter',' ', ...
'MultipleDelimsAsOne',true, 'CollectOutput',true);
fclose(fid);
H = H{1}; C = C{1};
but it wont read the files.can anyone help me with this code. I somehow undesratnd the alphabets inside the filenames doing wrong,but.. I really appreciate any comment. Thank you
#BTW each .dat file has 21line of header and 80000 row of data come after it.

Best Answer

You are mixing up two different paradigms for handling multiple files: first you use dir to get all of the names of any .dat files in some folder... and then you totally ignore those filenames and instead try to generate names using num2str and string concatenation. There is no point in trying to mix everything together like that: just use dir to get the filenames, and then use them! Try something like this instead:
opt = {'Delimiter',' ', 'MultipleDelimsAsOne',true, 'CollectOutput',true};
D = './Site';
S = dir(fullfile(D,'*.dat'));
S = natsortfiles(S); % alphanumeric sort by filename
for k = 1:numel(S)
[fid,msg] = fopen(fullfile(D,S(k).name),'rt');
assert(fid>=3,msg)
H = textscan(fid, '%s', 21, 'Delimiter','\n');
C = textscan(fid, repmat('%f ',1,8), opt{:});
fclose(fid);
...
end
You can download natsortfiles here (it is optional):