Read set of .dat files in for loop
조회 수: 3 (최근 30일)
이전 댓글 표시
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
채택된 답변
Stephen23
2021년 7월 15일
편집: Stephen23
2021년 7월 15일
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
Stephen23
2021년 7월 15일
@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.
추가 답변 (1개)
Turbulence Analysis
2021년 7월 15일
댓글 수: 1
Stephen23
2021년 7월 15일
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]
참고 항목
카테고리
Help Center 및 File Exchange에서 Text Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!