0

我目前有 20 个文本文件命名从 file1 到 file20。我正在使用将它们读入matlab

filePattern = 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 next file2 next file3 到 file20 的数据进入 Matlab。

但它正在重新排列为 file1 file10 file11 file12 ... file2 file20 并读取。dataFiles 是一种结构,文件按字母顺序加载。如何防止这种情况?

4

1 回答 1

3

我建议使用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}
于 2013-04-04T08:06:47.660 回答