Reading data from a text file
2 views (last 30 days)
Show older comments
Hi everyone!
I have a data text file with the first four lines that look like this:
0 {1123 13.17 4.90 3.05} {1303 13.52 9.78 6.74}
1
2 {685 24.39 26.71 13.36}
3 {685 24.33 26.60 13.78} {1045 24.31 21.47 14.67}
The first line begins with "0" followed by two sets of data enclosed by {}
The second line begins with "1" with no sets of data
The third line begins with "2" with 1 set set of data enclosed with {}
Lastly, the fourth line begins with 3 with 2 sets of data within {}
I cannot use textscan to read this data file since the format varies in each line. What I would like to do is to make it like this
For each line, I should get n by 4 matrix where n is the number of data sets enclosed by {}. Therefore I plan to have a Matlab variable C such that for each line = k, I get
for k=line
for n=number of data sets enclosed by {}
C{1,k}(n,4)
end
end
As an example for C{1,1}, I should get a 2 by 4 matrix of the form
1123 13.17 4.90 3.05
1303 13.52 9.78 6.74
Please help me how to make this work.
Thanks,
Bry
0 Comments
Accepted Answer
Sven
on 2 Sep 2012
Edited: Sven
on 2 Sep 2012
Hi Bry
This code should work just fine to do what you describe. It uses a regular expression at each line of the text file to match the "{1 2 3 4}" pattern:
fid = fopen('myFile.txt');
allMatches = cell(1000,1); % Just initialise to some large number
cellNo = 0;
tline = fgetl(fid);
while ischar(tline)
matchedStrs = regexp(tline, '\{[^\{]*\}','match');
if ~isempty(matchedStrs)
cellNo = cellNo + 1;
cellContents = cell2mat(cellfun(@(str)cell2mat(textscan(str,'{%f %f %f %f}',1)),matchedStrs','Un',0));
allMatches{cellNo} = cellContents;
end
tline = fgetl(fid);
end
fclose(fid);
allMatches = allMatches(1:cellNo); % Trim off the empty cells that we initialised
More Answers (0)
See Also
Categories
Find more on Text Data Preparation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!