Reading CSV files in a sequence based on numeric value in file name
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Sunny
le 16 Fév 2019
Réponse apportée : Are Mjaavatten
le 19 Fév 2019
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 commentaires
Réponse acceptée
Are Mjaavatten
le 19 Fév 2019
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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur String Parsing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!