readtable

Reads a delimited text or spreadsheet file into a table.

Category: Language Fundamentals > Data Types

Syntax

T = readtable(filename)

Reads the file, taking variable names from the first row and detecting the type of each column.

T = readtable(filename, opts)

Reads using an import options object.

T = readtable(___, Name, Value)

Adjusts reading with options such as 'Range' or 'VariableNamingRule'.

Description

readtable is the usual way to bring tabular data into the workspace. Column names come from the header line; characters that are not valid in a variable name are replaced (a name such as a;b becomes a_b) unless the naming rule is 'preserve'.

For control over types, missing-value markers or which columns to read, build an options object with detectImportOptions, change it with setvartype and setvaropts, and pass it as the second argument.

Input arguments

filename
Name of a .csv, .txt, .dat or spreadsheet file.
opts
Import options, for example from detectImportOptions.
'Range'
Cell range to read, such as 'A2:B3'.

Output arguments

T
Table with one variable per column. Numeric columns become double, text columns become cell arrays of character vectors.

Example

fid = fopen('data.csv', 'w');
fprintf(fid, 'x,y\n1,a\n2,b\n');
fclose(fid);
T = readtable('data.csv')
Output
T = 2×2 table

    x      y  
    _    _____

    1    {'a'}
    2    {'b'}

The example first writes a small file in the current folder.

Notes

In MatLivre strings that look like dates stay as text instead of becoming datetime; convert them afterwards with datetime.

Only comma-separated text is split into columns. A file separated by semicolons, tabs or spaces is read as a single column, and the 'Delimiter' option has no effect, so convert such files to commas first.

See also

writetable detectImportOptions readtimetable readmatrix table