matlabiotextscan

Read Large Text File with a While Loop into MATLAB


I am trying to read a large 3 GB text file into MATLAB, organized by a header with names, and with a delimiter of a space (see below fruit.txt) However, the only data needed is the Grapes Column. Since it is a huge file, I am using a loop below to only read in one column into Matlab. How can I read in only one column of data with the loop below? I have to use a loop and preselection of needed columns since the file is over 3 GB of data.

fruit.txt

Apples Grapes Oranges
3 4 A
4 G 1
6 A 3 
3 4 1
A 6 1
2 2 4

filename = 'fruit.txt'
delimiter = ' ';
formatSpec = '%s%s%s[^\n\r]';

fileID  = fopen(filename, 'r' ) ;
out = {};
k = 0 ;

while ~feof(fileID)
  k = k+1;
  C = textscan(fileID, formatSpec, 'Delimiter', delimiter);

  out{end+1} = Grapes{:,2}; 
end

Solution

  • Use readmatrix and specify one header row and that you only want column 2:

    readmatrix(filename, 'FileType','text', 'Delimiter', delimiter, 'NumHeaderLines', 1, 'Range', 'B:B');