Using fscanf to read in data
35 ビュー (過去 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!