textscan

Reads formatted data from a file or text into a cell array of columns.

Category: Data Import and Analysis > Data Import and Export

Syntax

C = textscan(fid, formatSpec)

Reads from an open file.

C = textscan(str, formatSpec)

Reads from a character vector.

C = textscan(..., Name, Value)

Sets options such as 'Delimiter' and 'HeaderLines'.

Description

The format is applied again and again until the input ends, so each conversion collects one column. %d gives int32 and %f gives double. Join numeric columns of the same class with [C{:}].

Because the result holds columns of different types, textscan suits files that mix text and numbers, where readmatrix cannot.

Input arguments

formatSpec
Conversions such as %f, %d, %s, one per column. Literal text in the format must match the data.
'Delimiter'
Field separator or cell array of separators.
'HeaderLines'
Number of lines to skip at the start.

Output arguments

C
Cell array with one cell per conversion: numeric column vectors, or cell arrays of character vectors for %s.

Example

Text and numbers

C = textscan('a 1 b 2 c 3', '%s %f');
C{1}'
C{2}'
D = textscan('10:20 30:40', '%d:%d');
[D{:}]
fid = fopen('t.csv', 'w'); fprintf(fid, 'id,val\n1,2.5\n2,3.5\n'); fclose(fid);
fid = fopen('t.csv');
E = textscan(fid, '%d %f', 'Delimiter', ',', 'HeaderLines', 1);
fclose(fid);
E{2}'
Output
ans = 1×3 cell

    {'a'}    {'b'}    {'c'}
ans = 1×3

     1     2     3
ans = 2×2 int32 matrix

   10   20
   30   40
ans = 1×2

    2.5000    3.5000

See also

textread fscanf readtable readcell strsplit