fscanf
Reads formatted data from a text file.
Category: Data Import and Analysis > Data Import and Export
Syntax
A = fscanf(fid, formatSpec)
Reads values matching the format until the end of the file, into a column.
A = fscanf(fid, formatSpec, sizeA)
Limits or shapes the result: n, Inf or [m n].
[A, count] = fscanf(...)
Also returns the number of values read.
Description
Because matrices are filled by columns, reading a file written row by row into a matrix needs a transpose: fscanf(fid, '%d', [3 Inf])' for rows of three numbers.
Reading stops at the first piece of text that does not match the format. For mixed text and numbers, textscan is more flexible.
Input arguments
formatSpec- Conversions such as
%d,%f,%g,%s,%c. The format is reused until the data or the size is exhausted. sizeA[m Inf]reads as many columns as the data provides. Values fill the matrix column by column.
Output arguments
A- Numeric column vector or matrix; text conversions give character codes mixed in unless all conversions are text.
count- Number of elements read.
Example
Rows of numbers
fid = fopen('n.txt', 'w');
fprintf(fid, '1 2 3\n4 5 6\n');
fclose(fid);
fid = fopen('n.txt');
A = fscanf(fid, '%d', [3 Inf])'
fclose(fid);
fid = fopen('n.txt');
[B, count] = fscanf(fid, '%f');
fclose(fid);
B', count
Output
A = 2×3
1 2 3
4 5 6
ans = 1×6
1 2 3 4 5 6
count = 6