Read 'm-to-n' row numbers from a txt file (MATLAB)

2.2k views Asked by At

I'm trying to read data from a .txt file. The sample data is given below. I need an algorithm to read just M-N row numbers. While I can use while/for loops, I'm afraid that it might become very slow. Thanks!

a=[  1 6 11 16 ; 
     2 7 12 17 ; 
     3 8 13 18 ; 
     4 9 14 19 ; 
     5 10 15 20] ;    % data is in Test.txt --> 
                      % fid = fopen('Test.txt');
                      % a=a.'; fprintf(fid, '%.3f\t%.3f\t%.3f\t%.3f\r\n', a(:)) ;

fid = fopen('Test.txt') ;
AnsMat = fscanf(fid, '%f %f %f %f')

AnsMat = [2 7 12 17 ; 3 8 13 18] ;  % Read row-numbers 2 to 4 this time
2

There are 2 answers

3
mathematical.coffee On BEST ANSWER

You could try textscan which allows a HeaderLines parameter telling matlab how many lines to skip.

For example to read lines n (=2) to m(=4), you could do:

fid = fopen('Test.txt');
C   = textscan(fid,'%f %f %f %f\n',m-n+1,'HeaderLines',n-1);
fclose(fid);

This does return the data as a cell array though so you have to convert it:

AnsMat = cell2mat(C);
1
prototoast On

If your data were in csv format instead of text format, you could use the command:

text=csvread('yourfile.csv',1,1,[1 1 m n])

Obviously, if your data is only available in text format, it would be just as much work to manually convert it as it would be to use the textscan option, but if your text file is being generated elsewhere where you would have control over the output format, this may streamline the process.