How to Read Excel Files in MATLAB: Simple Guide
In MATLAB, you can read Excel files using the
readtable function for tables or xlsread for numeric data. Use readtable('filename.xlsx') to load the data into a table variable easily.Syntax
The main functions to read Excel files in MATLAB are:
readtable(filename): Reads data into a table, including text and numbers.xlsread(filename): Reads numeric data, text, and raw data (older function).readmatrix(filename): Reads numeric data into a matrix.
Replace filename with your Excel file path.
matlab
T = readtable('data.xlsx'); [num, txt, raw] = xlsread('data.xlsx'); M = readmatrix('data.xlsx');
Example
This example shows how to read an Excel file named sample.xlsx into a table and display the first few rows.
matlab
filename = 'sample.xlsx';
T = readtable(filename);
disp(head(T));Output
Name Age Score
____ _____ _____
Amy 25 88
Bob 30 92
Cara 22 79
Dan 28 85
Eva 24 90
Common Pitfalls
Common mistakes when reading Excel files in MATLAB include:
- Using
xlsreadon large files can be slow; preferreadtableorreadmatrix. - Not specifying the correct sheet or range if your data is not on the first sheet.
- File path errors: ensure the Excel file is in the current folder or provide the full path.
- Data type mismatches:
readtablehandles mixed data better thanxlsread.
Example of specifying sheet and range:
matlab
T = readtable('sample.xlsx', 'Sheet', 'Sheet2', 'Range', 'A1:C10');
Quick Reference
| Function | Description | Best Use Case |
|---|---|---|
| readtable(filename) | Reads Excel data into a table | Mixed data with text and numbers |
| xlsread(filename) | Reads numeric and text data (older) | Simple numeric data or legacy code |
| readmatrix(filename) | Reads numeric data into a matrix | Pure numeric data without text |
Key Takeaways
Use readtable to read Excel files with mixed data types easily.
Specify sheet and range if your data is not on the first sheet.
Avoid xlsread for large files; prefer readtable or readmatrix.
Ensure the Excel file path is correct to avoid file not found errors.
readmatrix is best for numeric-only Excel data.