How to Write Excel Files in MATLAB Quickly and Easily
In MATLAB, you can write data to Excel files using the
writematrix, writecell, or writetable functions. These functions save your data directly to an Excel file with a specified filename and sheet name.Syntax
Here are the main functions to write data to Excel in MATLAB:
writematrix(data, filename): Writes numeric or mixed data matrix to Excel.writecell(data, filename): Writes cell arrays (mixed types) to Excel.writetable(table, filename): Writes table data to Excel.- Optional parameters include specifying the sheet name and range.
matlab
writematrix(data, filename) writematrix(data, filename, 'Sheet', sheetname) writecell(data, filename) writecell(data, filename, 'Sheet', sheetname) writetable(table, filename) writetable(table, filename, 'Sheet', sheetname)
Example
This example shows how to write a numeric matrix and a table to an Excel file named data.xlsx on the sheet Sheet1.
matlab
data = [10, 20, 30; 40, 50, 60]; writematrix(data, 'data.xlsx', 'Sheet', 'Sheet1'); T = table({'Alice'; 'Bob'}, [25; 30], 'VariableNames', {'Name', 'Age'}); writetable(T, 'data.xlsx', 'Sheet', 'Sheet2');
Output
Creates 'data.xlsx' with numeric data on Sheet1 and table data on Sheet2.
Common Pitfalls
Common mistakes when writing Excel files in MATLAB include:
- Not specifying the correct sheet name, which defaults to the first sheet.
- Trying to write unsupported data types directly (e.g., structures) without converting.
- Overwriting existing files unintentionally without backup.
- Using
xlswritewhich is legacy and less reliable thanwritematrixandwritetable.
matlab
%% Wrong way (legacy and less reliable) xlswrite('data.xlsx', data); %% Right way (modern and recommended) writematrix(data, 'data.xlsx');
Quick Reference
| Function | Purpose | Data Type Supported | Notes |
|---|---|---|---|
| writematrix | Write numeric or mixed matrix data | Numeric arrays, mixed numeric and text | Recommended for matrices |
| writecell | Write cell arrays | Cell arrays with mixed types | Use for mixed data types |
| writetable | Write table data | Table objects | Best for tabular data with variable names |
| xlswrite (legacy) | Write data to Excel | Numeric and cell arrays | Legacy, avoid if possible |
Key Takeaways
Use writematrix, writecell, or writetable to write data to Excel files in MATLAB.
Specify the sheet name to control where data is saved in the Excel file.
Avoid using the legacy xlswrite function for better reliability and features.
Ensure your data is in a supported format before writing to Excel.
Always check if the file exists to avoid accidental overwriting.