0
0
MatlabHow-ToBeginner ยท 3 min read

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 xlswrite which is legacy and less reliable than writematrix and writetable.
matlab
%% Wrong way (legacy and less reliable)
xlswrite('data.xlsx', data);

%% Right way (modern and recommended)
writematrix(data, 'data.xlsx');
๐Ÿ“Š

Quick Reference

FunctionPurposeData Type SupportedNotes
writematrixWrite numeric or mixed matrix dataNumeric arrays, mixed numeric and textRecommended for matrices
writecellWrite cell arraysCell arrays with mixed typesUse for mixed data types
writetableWrite table dataTable objectsBest for tabular data with variable names
xlswrite (legacy)Write data to ExcelNumeric and cell arraysLegacy, 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.