我目前有20个文本文件命名从file1开始到file20。我正在使用
将它们读入matlabfilePattern = fullfile(myFolder, '*.txt');
dataFiles = dir(filePattern);
for k = 1:length(dataFiles)
baseFileName = dataFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fid = fopen(fullFileName, 'r');
line = fgetl( fid );
while ischar( line )
tks = regexp( line, '\[([^,]+),([^\]]+)\]([^\[]+)\[([^\]]+)\]([^\[]+)', 'tokens' );
for ii = 1:numel(tks)
j=j+1;
mat( j ,: ) = str2double( tks{ii} );
end
line = fgetl( fid );
end
fclose( fid );
end
它工作正常,但我需要保留文本文件在文件夹中出现的相同顺序。从file1下载file2下一个file3到file20到Matlab的数据。
但它正在重新排列到file1 file10 file11 file12 ... file2 file20并阅读。 dataFiles是一种结构,文件按字母顺序加载。如何防止?
答案 0 :(得分:2)
我建议使用sort_nat(在Matlab Central上提供)来执行此任务。
在空文件夹中运行:
% create sample files
for i = 1:20
filename = sprintf('file%d.txt',i);
fclose(fopen(filename, 'w'));
end
% obtain folder contents
files = dir('*.txt');
%{files.name} % -> list of files might be in alphabetical order (depends on OS)
% sort_nat sorts strings containing digits in a way such that the numerical value
% of the digits is taken into account
[~,order] = sort_nat({files.name});
files = files(order);
% check output is in numerical order
{files.name}