Export MATLAB data to CSV

A practical review of exporting MATLAB data to CSV: which functions to use, what changes when data becomes delimited text, and how to check that the file stays accurate and usable.

Exporting MATLAB data to CSV turns values held in memory, such as a numeric matrix, a table or a cell array, into a plain-text file where fields are separated by commas and records by line breaks. This is useful because almost every spreadsheet, database and scripting language can read CSV. The cost is that CSV stores only text. Data types, precision choices, units and metadata are either reduced to characters or dropped. This review explains what the conversion changes, which MATLAB functions fit which data, and how to confirm the result still means what you intended.

Is CSV export suitable for your intended use?

CSV is a good choice when the data is tabular, when the destination is another program or person who does not use MATLAB, and when you need a format that can be inspected in any text editor. Its main benefit is portability.

The decisive tradeoff is fidelity. A CSV file does not record whether a column held doubles, integers, logicals, categoricals, strings or datetimes. It also does not record dimensions beyond two, variable units or descriptions. Whatever program opens the file has to guess types from the text.

Another format is usually better in these cases:

  • You will reload the data only in MATLAB. A MAT-file saved with save keeps types, sizes and variable names intact.
  • The data has more than two dimensions, nested structures, or mixed content that does not reduce cleanly to rows and columns.
  • You need exact round-tripping of floating-point values and cannot verify the precision that was written.
  • The recipient specifically works in Excel and needs multiple sheets or cell formatting. writetable can write a spreadsheet file directly when given an .xlsx file name.

Which MATLAB function to use

Current MATLAB documentation recommends a small set of functions, each matched to a type of data in memory:

Data in memory | Recommended function | Notes
Numeric or logical matrix | writematrix | Writes values only, with no header row.
Table or timetable | writetable | Writes variable names as a header row by default.
Cell array | writecell | Handles mixed text and numbers in a cell array.
Structure | writetable after struct2table | Works when the fields convert to table columns.
Older code using csvwrite or dlmwrite | Migrate to the functions above | Documentation lists both as not recommended. csvwrite documentation notes it writes a limited number of significant digits.

The table above reflects documented guidance. Option names and default behavior can differ between MATLAB releases, so check the documentation for the release you have installed.

What the export actually changes

Several terms used for other text tools do not apply here. Exporting to CSV does not reverse, mirror or restyle characters, and the word "font" has no meaning in a CSV file. The conversion serializes data. Each value is formatted as characters, delimiters are placed between fields, and line breaks are placed between rows. Any visual appearance you later see, such as column widths or number formatting in a spreadsheet, is applied by the program displaying the file. It is not stored in the CSV.

A simple numeric example shows the mechanism:

A = [1 2; 3 4];
writematrix(A, 'data.csv')

% data.csv contains:
1,2
3,4

A table adds a header row taken from its variable names:

T = table([1;2], ["a";"b"], 'VariableNames', {'id','label'});
writetable(T, 'results.csv')

% results.csv contains:
id,label
1,a
2,b

These are the main ways meaning can shift during export:

  • Numeric precision: floating-point values are converted to decimal text. Whether every digit needed for an exact round trip is written depends on the function and release. Legacy functions are the most likely to truncate.
  • Types: logicals, categoricals and integers all become plain characters. A reader cannot tell that 1 meant true or that a column was categorical.
  • Dates and times: datetime values are written as text in a display format. Time zone and sub-second detail may be lost if the format does not include them.
  • Text containing delimiters: a comma, quote or line break inside a text value must be quoted, or it will split the field. writetable has a QuoteStrings option, and its default has varied by release.
  • Missing values: NaN, missing strings and undefined categoricals become empty fields or text tokens. The receiving program may read these differently.
  • Delimiter: the 'Delimiter' option can produce tab, semicolon or other separated files. A file with a .csv name but a different delimiter can confuse some readers.

Will the file remain readable and usable after sharing?

Because CSV is plain text, it copies, pastes, emails and version-controls cleanly, and no special characters are involved in the structure itself. Problems usually come from how the receiving program interprets the text.

  • Spreadsheet locale: in regions where the comma is the decimal separator, spreadsheet programs may expect semicolons as the field delimiter. A comma-delimited file can then open as a single column. Writing with a semicolon delimiter, or importing through the program's text import tool, avoids this.
  • Automatic type guessing: spreadsheets may convert long numeric identifiers, leading-zero codes or date-like strings into numbers or dates. Opening the file in a text editor shows what was actually stored.
  • Character encoding: non-ASCII text in labels or values must be read using the same encoding it was written with. writetable accepts an 'Encoding' option. Confirm which encoding your recipient expects.
  • Accessibility: a CSV file has no visual layout of its own, so screen readers depend on the application used to open it. A header row with descriptive variable names makes columns easier to identify. No assistive-technology testing was available for this review, so check behavior in the specific application your readers use.

A practical verification step

The most reliable check is to read the file back and compare it with the original. This catches precision loss, type changes and quoting problems before the file is shared.

writetable(T, 'results.csv');
T2 = readtable('results.csv');

% Compare numeric columns within a tolerance, and inspect
% text, date and categorical columns by eye or with isequal.
max(abs(T.id - T2.id))

Two cautions about this check. A successful round trip in MATLAB does not guarantee the destination program reads the file the same way, so open it there too. Also, readtable makes its own type guesses, so a column may return as a different type than it started as.

Gaps in this review

No release-specific testing, performance measurements or comparisons across destination programs were available. The guidance above is based on documented MATLAB function roles and general properties of delimited text. Defaults such as quoting behavior, numeric precision and encoding should be confirmed against the documentation and a test export in your own environment.

Bottom line

For sharing two-dimensional data with other tools, exporting to CSV with writematrix, writetable or writecell is a sound choice, provided you check precision, quoting, dates and encoding against a read-back of the file. When the data will stay in MATLAB, or when types and metadata matter more than portability, a MAT-file or a spreadsheet file will preserve more of the original meaning.