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!