1
votes

I have some text files (1.txt, 2.txt,..., 60.txt) and all of them have 5 lines of header. I use the following codes, but it cannot recognize the headers and import all of the data. How I can say the matlab to start importing from a specific line?

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
2

2 Answers

2
votes

IMPORTDATA has 2 additional parameters: delimiterIn and headerlinesIn.

So you use (assuming tab as a delimiter):

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

I'd also recommend to preallocate the data matrix.

Notice that for your code to work make sure all input files have the same size. Otherwise you will get error in data(:,n)=img(:); (yes, use n instead of i).

For above two issues you can insert into the loop:

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
0
votes

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.