Categories &

Functions List

Function Reference: readtable

datatypes: tbl = readtable (filename)
datatypes: tbl = readtable (filename, Name, Value)

Read a file into a table, detecting variable types automatically.

tbl = readtable (filename) reads the file named by filename (a character vector or string scalar) and returns it as a table. The file type is inferred from the extension: .txt, .csv, and .dat are read as delimited text; .ods and .fods are read as OpenDocument spreadsheets. Use the 'FileType' option to override the inferred type.

By default the first row supplies the variable names and each column’s data type is detected automatically (numeric, datetime, duration, or text). The following Name-Value options are supported:

NameValue
'FileType''text' or 'spreadsheet'.
'ReadVariableNames'Logical; read the first row as variable names (default true).
'ReadRowNames'Logical; read the first column as row names (default false).
'Delimiter'Field delimiter for text files: a single character or one of 'comma', 'space', 'tab', 'semi', 'bar' (default ',').
'NumHeaderLines'Number of lines to skip before the header (default 0).
'TextType''char' or 'string' for text columns (default 'char').
'VariableNamingRule''modify' or 'preserve' (default 'modify').
'Sheet'Spreadsheet only: the sheet to read, selected by name or by a 1-based index over the data sheets (default: the first sheet).
'Range'Spreadsheet only: an A1-style range such as 'C5' or 'C5:D8' limiting the region read.

Source Code: readtable

Office Open XML spreadsheets (.xlsx, .xlsm) are read via the same interface as ODS. The legacy binary formats .xls and .xlsb are not supported; use .xlsx, .ods, or a text format.

See also: writetable, csv2table, ods2table

Source Code: readtable

Example: 1

readtable is the unified, MATLAB-compatible reader: it picks text vs spreadsheet from the file extension. Here it reads a comma-delimited file, taking the first row as variable names and detecting each column's type.

 T = table ([38; 43], [71.5; 69.0], 'VariableNames', {'Age', 'Height'});
 filename = fullfile (tempdir (), 'patients.csv');
 writetable (T, filename);
 readtable (filename)
ans =
  2x2 table

    Age    Height    
    ___    ______    

     38      71.5    
     43        69

Example: 2

Options let you override the defaults — for example read a specific spreadsheet 'Sheet', or turn the first column into row names.

 filename = fullfile (tempdir (), 'patients.ods');
 T = table ([38; 43], 'VariableNames', {'Age'}, 'RowNames', {'Li', 'Diaz'});
 writetable (T, filename, 'WriteRowNames', true);
 readtable (filename, 'ReadRowNames', true)
ans =
  2x1 table

            Age    
            ___    

    Li       38    
    Diaz     43
 delete (filename);