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!