How can I read a text file containing different number of values on each line using MATLAB 7.8 (R2009a)?

3 views (last 30 days)
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?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 30 Jun 2010
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.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R2009a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!