Read a textfile in MATLAB
Show older comments
I am using MATLAB to call another application which generates a huge text file of the results I want. I'm looking for a way to scan for lines which contain specific strings, retrieve specific numeric values from those lines and store them in a numeric array.
I've been using the following code:
fid = fopen('filename.txt');
var1 = textscan(fid,'%s','delimiter','\n');
lines = var1{1,1};
Since textscan creates a cell which has the whole text file as the first entry in that cell, I declare lines as a secondary variable to get get the text in separate lines.
Thereafter, I use the following code:
if strfind(lines{i}, 'String Sequence')== 1
line2 = char(lines{i});
This converts the lines{i} cell to a string. I need to retrieve specific numeric values from this string:
1. I know the position where the values I need are located in this string. 2. I know the string sequence which precedes these values.
For example the string retrieved could read:
line2 =
The fare for a 7% ROI = 343.24 DOLLARS/PASS
For multiple runs, the structure of the string remains the same, only the numeric value - 343.24 in this case - varies. Can someone suggest a way to implement the seach logic described above.
My program generates a text file with some 20,000 lines at each optimization run. Is there a better (faster) way of implementing the text search?
4 Comments
dpb
on 1 Oct 2013
Are the number of lines known/constant?
Is this the only line you care about?
Gautam Marwaha
on 1 Oct 2013
Matt Kindig
on 1 Oct 2013
Can you clarify what data you are trying to extract? Just the number in front of DOLLARS/PASS (as Cedric's answer below), or additional information?
Gautam Marwaha
on 1 Oct 2013
Accepted Answer
More Answers (0)
Categories
Find more on Characters and Strings 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!