Read set of .dat files in for loop

3 views (last 30 days)
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));

Accepted Answer

Stephen23
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
Turbulence Analysis
Turbulence Analysis on 15 Jul 2021
Hi,
Many thnaks for the response.. I got the below error
Undefined function or variable 'readmatrix'
Stephen23
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.

Sign in to comment.

More Answers (1)

Turbulence Analysis
Turbulence Analysis on 15 Jul 2021
I tried as follows, It's working perfectly..
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);
F1 = fopen(F);
data = textscan(F1, '%f %f %f');
data = cell2mat(data);
data1 (:,k) = mean (data (:,2));
end
  1 Comment
Stephen23
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]

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!