Read data from text file
A = fscanf(fileID, format)
A = fscanf(fileID, format, sizeA)
[A, count] = fscanf(...)
A = fscanf(fileID, format) reads and converts data from a text file into array A in column order. To convert, fscanf uses the format and the encoding scheme associated with the file. To set the encoding scheme, use fopen. The fscanf function reapplies the format throughout the entire file, and positions the file pointer at the end-of-file marker. If fscanf cannot match the format to the data, it reads only the portion that matches into A and stops processing.
A = fscanf(fileID, format, sizeA) reads sizeA elements into A, and positions the file pointer after the last element read. sizeA can be an integer, or can have the form [m,n].
[A, count] = fscanf(...) returns the number of elements that fscanf successfully reads.
Integer file identifier obtained from fopen.
String enclosed in single quotation marks that describes each type of element (field). Includes one or more of the following specifiers.
Dimensions of the output array A. Specify in one of the following forms:
When the format includes %s, A can contain more than n columns. n refers to elements, not characters.
An array. If the format includes:
If MATLAB cannot match the input to the format, and the format contains both numeric and character specifiers, A can be numeric or character. The class of A depends on the values MATLAB reads before processing stops.
The number of elements fscanf reads into A.
Read the contents of a file. fscanf reuses the format throughout the file, so you do not need a control loop:
% Create a file with an exponential table x = 0:.1:1; y = [x; exp(x)]; fid = fopen('exp.txt', 'w'); fprintf(fid, '%6.2f %12.8f\n', y); fclose(fid); % Read the data, filling A in column order % First line of the file: % 0.00 1.00000000 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';
Skip specific characters in a file, and return only numeric values:
% Create a file with temperatures tempstr = '78°F 72°F 64°F 66°F 49°F'; fid = fopen('temperature.dat', 'w+'); fprintf(fid, '%s', tempstr); % Return to the beginning of the file frewind(fid); % Read the numbers in the file, skipping the units % num_temps is a numeric column vector degrees = char(176); num_temps = fscanf(fid, ['%d' degrees 'F']); fclose(fid);
Format specifiers for the reading functions sscanf and fscanf differ from the formats for the writing functions sprintf and fprintf. The reading functions do not support a precision field. The width field specifies a minimum for writing but a maximum for reading.