Reading CSV files in a sequence based on numeric value in file name
조회 수: 2 (최근 30일)
이전 댓글 표시
Hello,
I am trying to read files in a sequence based on a numeric value in file name. The file names are shown a below. The numeric value at the end of each file is in a sequence. I am trying below code but this doesn't work. I am sure that I am doing something wrong with the * symbol placement.
Walk_ACLR_055_041_PSI_15_15_data_44.csv, Walk_ACLR_247_135_PSI_15_15_data_3.csv, Walk_ACLR_271_155_PSI_15_15_data_17.csv ......
clc;clear;
Labels = [];
for k = 1:150
if exist (['*',num2str(k),'.csv'],'file')
filename = ['*',num2str(k),'.csv']
T = readtable(filename);
H = height(T);
Total = H/15;
Labels = [Labels;Total];
end
end
댓글 수: 0
채택된 답변
Are Mjaavatten
2019년 2월 19일
d = dir('*.csv');
filenames = {};
index = 0;
k = 0;
for i = 1:length(d)
% Using regexp with lookaround on the file name to find
% a sequence of digits preceeded by '_' and followed by '.':
no = regexp(d(i).name,'(?<=_)\d*(?=\.)','match');
if ~isempty(no)
k = k+1;
filenames{k} = d(i).name;
index(k) = str2num(no{end});
end
end
% filenames contains all filenames of the correct form
% index contains the numeric value
% Now sort:
[~,ix] = sort(index);
filenames = filenames(ix);
% You can now process files in the correct order:
for i = 1:length(index)
disp(filenames{i}); % or whatever...
end
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 String Parsing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!