table

Methods

Method Reference: table.table2csv

table: table2csv (tbl, file)

Write a table to a comma-separated-value (CSV) file.

table2csv (tbl, file) writes the table tbl to file, which may be a character vector, a cellstr, or a string scalar. The resulting file can be read back with csv2table.

The file begins with a comment line reporting how many consecutive rows hold the variable types, names, descriptions, and units, in that order. Those header rows are followed by one row of data per table row.

Variables are serialized as follows:

  • Numeric and logical variables are written as numbers (logicals as 0/1). Missing and infinite values are written as the tokens NaN, NA, inf, and -inf.
  • Character, cellstr, and string variables are written as quoted text.
  • datetime, duration, calendarDuration, and categorical variables are written as their display strings.
  • A multicolumn variable is split into consecutive columns that share the same variable name.
  • A nested table is split into columns tagged with both the outer and the nested variable name. A structure is split into one column per field, tagged with the variable name and the field name.

When tbl has row names they are written under a leading RowNames column. Variable descriptions and units are written whenever any variable has a non-empty description or unit, respectively (the others are left empty).

Note the following round-trip limitations when reading the file back with csv2table: calendarDuration and categorical variables are returned as cell arrays of character vectors (their values are not reconstructed), missing string values are read back as empty strings, and datetime and duration display formats are not preserved, although the values themselves are exact.

Source Code: table

Example: 1

table2csv writes a table to CSV in the package's round-trippable format: a metadata comment line, then header rows for the variable types, names, and units, followed by one row of data per table row.

 Age = [38; 43; 40];
 Height = [71; 69; 64];
 T = table (Age, Height)
T =
  3x2 table

    Age    Height    
    ___    ______    

     38        71    
     43        69    
     40        64
 T.Properties.VariableUnits = {'Yrs', 'in'};
 filename = fullfile (tempdir (), 'patients.csv');
 table2csv (T, filename);
 type (filename)
"# varTypes 1 rows; varNames 1 rows; varDescriptions 0 rows; varUnits 1 rows.",
"double","double"
"Age","Height"
"Yrs","in"
38,71
43,69
40,64

Because the type and unit metadata is preserved in the header, csv2table reconstructs the table faithfully.

 csv2table (filename)
ans =
  3x2 table

    Age    Height    
    ___    ______    

     38        71    
     43        69    
     40        64
 delete (filename);