Dificulty on fscanf with '%s'
4 views (last 30 days)
Show older comments
Hello. I'm trying to read a text file with string and numbers. Exactly this: CSIRO 1 2.563 29.251 21.140 1.194 1007.258 19.872
I tried to read with fscanf the string and the numbers at the same time, but it writes in my matrix the strings as ascii code for each character. So I put a '%*s' to jump the string, read only the numbers first, and then try to read only the string in another matrix. I made this:
-- to read the numbers file(imod) = fopen(char(arq)); fgetl(file(imod)); %pula primeira linha meteoro = fscanf(file(imod),['%*s' '%d' repmat('%f',1,6)],[7,inf]); Prec(imod,:) = meteoro(2,1:7670); and go on.....
-- then to read the string frewind(file(imod)); fgetl(file(imod)); %pula primeira linha nome = fscanf(file(imod),['%s'],[1,inf]);
I've tried many different formats, like '%6c', or '%s \n' in order to read the string and jump the rest... but or I get the full line in my matrix, or it reads the first character and jump to the next number. I don't get how did MAtLab in the first reading jumped the string correctly and read the numbers, but it doesn't work reading only the string.
Some ideas?
Thank you very much, I'm almost giving up.
0 Comments
Accepted Answer
dpb
on 18 Sep 2013
Edited: dpb
on 18 Sep 2013
Yeah, fscanf format scanning is a pita for mixed fields owing to the penchant of %s to read everything.
Here's where textscan is your friend; it has been specifically cleaned up to deal with the various field types more cleanly --
>> s='CSIRO 1 2.563 29.251 21.140 1.194 1007.258 19.872';
>> c=textscan(s,['%s' repmat('%f',1,7)],'collectoutput',true);
>> c{:}
ans =
'CSIRO'
ans =
1.0e+03 *
0.0010 0.0026 0.0293 0.0211 0.0012 1.0073 0.0199
>>
Just read from your open fid instead of course...
2 Comments
dpb
on 18 Sep 2013
textscan does return a cell array, yes...you can control the form returned to some degree with the format string and the 'collectoutput' property
doc textscan
for the full skinny, of course.
There's more info on accessing cell array contents in the section on cell arrays in the chapter on Data Types.
More Answers (0)
See Also
Categories
Find more on Large Files and Big Data in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!