MATLAB: How to read a text file containing different number of values on each line using MATLAB 7.8 (R2009a)

dataMATLABregexpsplitstringtokens

I am attempting to read data from a text file using MATLAB 7.8 (R2009a). Each line of the text file contains tokens which in this case are numbers separated by one or more spaces. Additionally, each line of the text file contains different number of tokens. As there are a different number of tokens on each line, I am unable to use the TEXTSCAN or FSCANF functions to read the data. Currently, I am reading data from the file element by element.
Is there a faster way to read data from this file?

Best Answer

The code snippet below illustrates how you can read data from a text file containing different number of tokens in every line of the file:
fp = fopen('myDataFile.txt', 'rt');
iter = 1;
while feof(fp) == 0
% Read the entire line of data
strInput = fgetl(fp);
% Remove any white spaces after the last number on the line.
strInput = regexprep(strInput, ' *$', '');
strNums = regexp(strInput, ' *', 'split');
numValues = cellfun(@str2num, strNums)
end
fclose(fp);
The code provided above will only work for versions MATLAB 7.5 (R2007b) and higher as the SPLIT option for the function REGEXP was introduced only in MATLAB 7.5 (R2007b).
For earlier versions, replace the following lines of code:
strNums = regexp(strInput, ' *', 'split');
numValues = cellfun(@str2num, strNums)
with
numValues = splitString(strInput)
where the function SPLITSTRING is available for download below.