Using fscanf to read in data
조회 수: 31 (최근 30일)
이전 댓글 표시
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
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
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Import and Export에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!