0
0
MatlabHow-ToBeginner ยท 3 min read

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 matrix A to a CSV file named filename.
  • writetable(T, filename): Writes table T to a CSV file, preserving variable names.
  • csvwrite(filename, A): Legacy function to write numeric matrix A to 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 csvwrite for tables or mixed data types, which causes errors.
  • Not specifying the .csv extension, 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

FunctionUse CaseNotes
writematrix(A, filename)Write numeric arraysRecommended for numeric data
writetable(T, filename)Write tables with mixed dataPreserves variable names as headers
csvwrite(filename, A)Legacy numeric array writingDoes 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.