1

我有一些文本文件(1.txt、2.txt、...、60.txt),它们都有 5 行标题。我使用以下代码,但它无法识别标题并导入所有数据。我怎么能说 matlab 从特定行开始导入?

num_txt=60;
input_dir='C:\data';

filenames=dir(fullfile(input_dir,'*.txt'));
i=1;
for n=1:num_txt    
    filename=fullfile(input_dir, filenames(n).name);
    img=importdata(filename);     
    data(:,i)=img(:);
    i=i+1;
end
4

2 回答 2

2

IMPORTDATA有 2 个附加参数:delimiterIn 和 headerlinesIn。

所以你使用(假设制表符作为分隔符):

img=importdata(filename,'\t',5);

我还建议预先分配data矩阵。

请注意,要使您的代码正常工作,请确保所有输入文件具有相同的大小。否则你会得到错误data(:,n)=img(:);(是的,使用n代替i)。

对于以上两个问题,您可以插入循环:

if n==1
    data = zeros(numel(img),num_txt);
else
    assert(numel(img)==size(data,1),'sprintf('File %s has different size', filenames(n).name))
end
于 2013-02-25T18:48:13.630 回答
0

I would recommend using readtext.m found here, if you know the basics and you don't want to spend much time on how to read text using MATLAB. But if you are learning, I suggest you do it yourself.

于 2013-02-25T19:39:09.367 回答