Using fscanf to read in data

13 views (last 30 days)
John
John on 4 Apr 2014
Answered: Alberto on 7 Apr 2014
Hello. I am supposed to read in a .txt file that has the following format:
string 12 78 (just another column of numbers)
string 35 63 ...
string 78 47 ...
string 45 12 ...
I need to read those in and then work with the numbers separately
I have to use the command fscanf as told by the instructor. my code is:
fid = fopen(abc.txt, 'r')
data = fscanf(fid, %s %d')
However the result turns out to be weird. What am I doing wrong with '%s %d' format?
Is there another way to read in this .txt file using fscanf?
  5 Comments
John
John on 4 Apr 2014
Oh and my abc.txt looks like this: (company name followed by money made each month in millions)
CompanyA 15 24 36 78 45 12 89 78 52 45 11 65
CompanyB ... (same, 12 columns of numbers)
CompanyC ... (same)
dpb
dpb on 4 Apr 2014
Edited: dpb on 5 Apr 2014
Well, as I said before, you've got to make the format match the record -- if there are 12 values/record besides the company name then
fmt=['%*s repmat('%d',1,3)];
becomes
fmt=['%*s repmat('%d',1,12)];
for the 12 values instead of the presumed 3 before.
Since it seems you'd want to keep the company ID as well, you'd be well served to forego the instructor's suggestion and use textscan instead.
Then you'll get a cell array that has the string company name as the first column and the remaining numeric data in the rest.
Or, you could use importdata and let it figure out the text in the left column automagically.
ADDENDUM:
Oh, on the "row-by-row" requirement...that entails using a loop and fgetl would be the simplest tool for that route. Not terribly efficient, of course. But, you could then use sscanf on the line and parse the company name off the left by either finding the first blank and using the length or if it's known to be a fixed length as your sample just hardcoding it for the purpose of a HW assignment.

Sign in to comment.

Answers (1)

Alberto
Alberto on 7 Apr 2014
You are right dpb, i think textscan is better in this case; the next code extract 3 columns according to the format described:
fid= fopen(filename);
a=textscan(fid, '%s %d %d')
fclose(fid)
Will extract a cell containing the three columns, first containing strings, and two others containing 32 bit signed integers.

Categories

Find more on Data Import and Export 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!