Reading CSV files in a sequence based on numeric value in file name

6 Ansichten (letzte 30 Tage)
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 ......
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];

Akzeptierte Antwort

Are Mjaavatten
Are Mjaavatten am 19 Feb. 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});
% 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...

Weitere Antworten (0)


Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange




Community Treasure Hunt

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

Start Hunting!

Translated by