필터 지우기
필터 지우기

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

채택된 답변

Are Mjaavatten
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개)

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by