Using fscanf to read in data

조회 수: 31 (최근 30일)
John
John 2014년 4월 4일
답변: Alberto 2014년 4월 7일
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
John
John 2014년 4월 4일
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 2014년 4월 4일
편집: dpb 2014년 4월 5일
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.

댓글을 달려면 로그인하십시오.

답변 (1개)

Alberto
Alberto 2014년 4월 7일
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.

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by