how to read file with name consist of number and string
22 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Samaneh Arzpeima
am 20 Sep. 2018
Bearbeitet: Stephen23
am 18 Apr. 2021
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.
1 Kommentar
Akzeptierte Antwort
Stephen23
am 21 Sep. 2018
Bearbeitet: Stephen23
am 18 Apr. 2021
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):
Weitere Antworten (1)
Krithika A
am 20 Sep. 2018
Go to the Home tab>import data. there you can select a single data set you want to use in matlab. Once there, you can create a function that you can use to import the same type of data sets. You can of course use this function in a for loop to import all the data sets at once. Look at the code to see what it's doing so you can use it in future.
Siehe auch
Kategorien
Mehr zu Large Files and Big Data finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!