以出现在Matlab中的顺序读取文件夹中的所有文本文件 [英] reading all the text files in a folder in same order they appear into Matlab

查看:1340
本文介绍了以出现在Matlab中的顺序读取文件夹中的所有文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有20个文本文件,命名从file1到file20.我正在使用

I am currently having 20 text files naming start from file1 to file20. I am reading them into matlab using

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

它工作正常,但是我需要保持文本文件在文件夹中出现的顺序.从文件1下一个文件2下一个文件3到文件20的数据到Matlab.

It is working perfectly, but I need to retain the same order the text files appear in the folder. The data from file1 next file2 next file3 till file20 into Matlab.

但是它正在重新排列为file1 file10 file11 file12 ... file2 file20并读取. dataFiles是一种结构,其中文件是按字母顺序加载的.如何预防呢?

But it is rearranging into file1 file10 file11 file12 ... file2 file20 and reading. dataFiles is a structure and in that the files are loaded alphabetically. How to prevent that?

推荐答案

我建议使用

I'd recommend using sort_nat (available on Matlab Central) for this task.

在一个空文件夹中运行它:

Run this in an empty folder:

% 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}

这篇关于以出现在Matlab中的顺序读取文件夹中的所有文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆