Read set of .dat files in for loop
8 views (last 30 days)
Show older comments
Turbulence Analysis
on 15 Jul 2021
Commented: Stephen23
on 15 Jul 2021
Hi,
I have set of .dat files as follows
a060_b000_C_mu.dat
a060_b003_C_mu.dat
a060_b006_C_mu.dat
a060_b009_C_mu.dat
.
.
.
.
a060_b060_C_mu.dat
As seen above, the only variable is second term in the file i.e. b000 to b060, I intend to read all the files using for loop and store the data in the matrix F3 as shown in the below code, could someone help me with this ??
F = fopen('a060_b000_C_mu.dat');
F1 = textscan(F, '%f %f %f');
F2 = cell2mat(F1);
F3 = mean (F2 (:,2));
0 Comments
Accepted Answer
Stephen23
on 15 Jul 2021
Edited: Stephen23
on 15 Jul 2021
P = 'absolute or relative path to where the files are saved';
F = fullfile(P,'a060_b*_C_mu.dat');
S = dir(F);
for k = 1:numel(S)
F = fullfile(P,S(k).name);
M = readmatrix(F);
S(k).data = mean(M(:,2));
end
V = vertcat(S.data) % optional
The data is stored in the non-scalar structure S, e.g. for the second file:
S(2).data % the mean data
S(2).name % the filename
2 Comments
Stephen23
on 15 Jul 2021
@Turbulence Analysis: you did not tell us the MATLAB version you are using, but apparently it does not include READMATRIX. You can replace that command with any suitable file-importing code, e.g. DLMREAD, TEXTSCAN, etc, just like you had in your original question.
More Answers (1)
Turbulence Analysis
on 15 Jul 2021
1 Comment
Stephen23
on 15 Jul 2021
Do not forget to FCLOSE every file that you FOPEN !
A more robust version of your code:
P = 'Y:\processed';
F = fullfile(P,'a060_b*_C_mu.dat');
S = dir(F);
for k = 1:numel(S)
F = fullfile(P,S(k).name);
fid = fopen(F);
tmp = textscan(fid,'%f%f%f');
fclose(fid); % you need this!
S(k).data = mean(data{2}); % simpler
end
data = [S.data]
See Also
Categories
Find more on Text Files 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!