How to Write CSV Files in MATLAB: Simple Guide
In MATLAB, you can write data to a CSV file using the
writematrix, writetable, or csvwrite functions. The writematrix function is recommended for numeric arrays, while writetable works well for tables with mixed data types. Simply provide your data and the filename with a .csv extension to save the file.Syntax
Here are the common ways to write CSV files in MATLAB:
writematrix(A, filename): Writes numeric matrixAto a CSV file namedfilename.writetable(T, filename): Writes tableTto a CSV file, preserving variable names.csvwrite(filename, A): Legacy function to write numeric matrixAto CSV.
Use .csv extension in filename to create a CSV file.
matlab
writematrix(A, 'filename.csv') writetable(T, 'filename.csv') csvwrite('filename.csv', A)
Example
This example shows how to write a numeric matrix and a table to CSV files using writematrix and writetable.
matlab
A = [1, 2, 3; 4, 5, 6]; writematrix(A, 'matrix.csv'); T = table([10; 20], {'apple'; 'banana'}, 'VariableNames', {'Quantity', 'Fruit'}); writetable(T, 'table.csv');
Output
Two files created: 'matrix.csv' with numeric data and 'table.csv' with table data including headers.
Common Pitfalls
Common mistakes when writing CSV files in MATLAB include:
- Using
csvwritefor tables or mixed data types, which causes errors. - Not specifying the
.csvextension, resulting in files with no extension. - Overwriting existing files without warning.
- Writing non-numeric data with
writematrix, which only supports numeric arrays.
Always choose writetable for tables and writematrix for numeric arrays.
matlab
% Wrong: writing table with csvwrite (causes error) T = table([1;2], {'a';'b'}); csvwrite('wrong.csv', table2array(T)); % This will fail if T contains non-numeric data % Right: use writetable writetable(T, 'right.csv');
Quick Reference
| Function | Use Case | Notes |
|---|---|---|
| writematrix(A, filename) | Write numeric arrays | Recommended for numeric data |
| writetable(T, filename) | Write tables with mixed data | Preserves variable names as headers |
| csvwrite(filename, A) | Legacy numeric array writing | Does not support tables or text |
Key Takeaways
Use writematrix to write numeric arrays to CSV files easily.
Use writetable to write tables with mixed data types and headers.
Always include the .csv extension in the filename.
Avoid csvwrite for tables or non-numeric data as it causes errors.
Check if the file exists to prevent accidental overwriting.