fscanf: how does the formatting string work?

4 views (last 30 days)
So looking at the example from Mathworks documentation:
% Create a file with an exponential table
x = 0:.1:1;
y = [x; exp(x)];
*Non-pertinent code omitted***
fid = fopen('exp.txt');
A = fscanf(fid, '%g %g', [2 inf]);
fclose(fid);
% Transpose so that A matches
% the orientation of the file
A = A';
Outputs a 11x2 matrix of numbers. Now, if I change the format field to:
  • '%g': Outputs the same 2-column matrix of numbers (still 11 rows)
  • '%f %g': Outputs the same 2-column matrix of numbers (still 11 rows)
  • '%s %g': Outputs a 28x2 matrix. Some of the entries (every 4th one to be exact) are the same as the original matrix. Everything else seems to be semi-random numbers, all between 46 and 57.
  • '%s': Outputs a 77x2 matrix. All random numbers.
What's going on here? I think there is something fundamental I'm not understanding about the fscanf.
Non-pertinent lines ommitted. Here's the link for the full example: http://www.mathworks.com/help/matlab/ref/fscanf.html

Accepted Answer

Walter Roberson
Walter Roberson on 21 Sep 2013
%f and %g are essentially equivalent for the purposes of fscanf(). Both of them tell fscanf() to read a number-like string and convert that string into numeric form which is what is output.
number-like strings can include an optional leading sign, optional leading 0's, optional digits 0-9, optional group of (a decimal point ('.'), optional more digits 0-9, the character 'e' or 'E', optional sign, optional leading 0's, optional digits for exponent). (Only some combinations are valid, but more are valid than you might expect.)
%s is for reading strings of any non-whitespace characters. whitespace includes space, tab, newline, carriage return, vertical tab, and formfeed. So for example the input
one,two, three
would match 'one,two,' because it would stop at the blank, not at the comma.
If you happen to read in number-like string as a string (without numeric conversion) then the characters that make up the number are what is returned, not the interpretation of the characters as a number. The input
3141
would be returned as '3141', not as decimal three thousand one hundred forty one.
If you then somehow convert the string to numeric form, what is shown would be the internal numeric representation of those characters. I happens that the internal numeric representation of the digit characters come out as decimal 48 (0) through 57 (9). So that's what you are seeing.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!