To read an Excel file in MATLAB, the fastest and most modern method is using the readtable function, which imports the spreadsheet into a table variable that preserves column headers and handles mixed data types. For example, running T = readtable('filename.xlsx') will load the first sheet of your Excel file into a table named T. This approach is generally preferred over older functions because it maintains the relationship between the data and its labels, making it much easier to perform data analysis, filtering, and visualization.
What You'll Need
- A computer with MATLAB installed (any recent version).
- An Excel file (.xlsx, .xls, or .xlsm) containing the data you wish to analyze.
- The Excel file must be saved in a directory that is currently on the MATLAB path, or you must know the full absolute file path to the document.
- Basic familiarity with the MATLAB Command Window or the Live Editor.
Step-by-Step
- Prepare Your Excel File: Before opening MATLAB, ensure your Excel spreadsheet is organized. For the most seamless import, place your column headers in the first row and your data immediately below them. Avoid merged cells, empty rows at the top of the sheet, or complex formatting like nested tables, as these can confuse the import engine and lead to missing data or incorrect column naming.
- Set Your Working Directory: Open MATLAB and look at the Current Folder browser. Ensure the folder containing your Excel file is the active directory. If it is not, use the folder icon in the toolstrip to navigate to the correct location. Alternatively, you can provide the full path in your code (e.g.,
'C:\Users\Name\Documents\data.xlsx'), but setting the directory simplifies the syntax. - Use the readtable Function: In the Command Window or a script, type the following command:
data = readtable('yourfile.xlsx');. Replace'yourfile.xlsx'with the actual name of your file. MATLAB will scan the file, detect the headers, and create a table object. This object allows you to access columns by name, such asdata.Temperature, rather than remembering column index numbers. - Specify a Specific Sheet or Range: If your data is not on the first sheet or only occupies a small section of a large file, use name-value arguments. To read a specific sheet, use:
data = readtable('yourfile.xlsx', 'Sheet', 'Results');. To read a specific cell range, use:data = readtable('yourfile.xlsx', 'Range', 'A1:C50');. Combining these allows you to target exactly the data you need without importing unnecessary noise. - Inspect the Imported Data: Once the command runs, double-click the variable in the Workspace browser to open the Variable Editor. This allows you to visually verify that the headers are correct and that numeric data has not been accidentally imported as text (strings). You can also type
head(data)in the Command Window to see the first few rows. - Convert Table to Array (Optional): If your subsequent analysis requires a numeric matrix rather than a table, you can convert the numeric parts of the table. Use
numericData = table2array(data);. Note that this only works if all columns in the table are numeric; if you have text headers or mixed types, you must first select the numeric columns using indexing, such asnumericData = table2array(data(:, 2:5));.
Common Mistakes
One of the most frequent errors is attempting to read a file that is currently open in Microsoft Excel. Depending on your operating system and MATLAB version, this can sometimes lead to a "Permission Denied" error because Excel places a lock on the file while it is active. It is always safer to close the spreadsheet before running your MATLAB script.
Another common pitfall is ignoring the data types of the imported columns. If a single cell in a numeric column contains a character (like a "N/A" string or a typo), MATLAB may import the entire column as a cell array of strings or a categorical array instead of a double-precision float. This will cause mathematical operations to fail. Always check the data types in the Workspace browser.
Users also frequently forget to use single quotes around the filename. In MATLAB, filenames are strings, and omitting the quotes will cause MATLAB to look for a variable with that name rather than a file on the disk, resulting in an "Undefined function or variable" error.
Finally, relying on xlsread is a common mistake for those following outdated tutorials. MathWorks has deprecated xlsread in favor of readtable, readmatrix, and readcell. Using the older function can lead to slower performance and less flexibility with modern .xlsx formats.
Tips
For users who prefer a visual interface over coding, MATLAB offers the "Import Data" tool. You can find this in the Home tab of the toolstrip. Clicking this button allows you to browse for your Excel file and opens an interactive window where you can select the range, choose the output type (Table, Column Vectors, or Matrix), and handle missing values visually. The best part is that once you have configured the import visually, you can click "Generate Script" to have MATLAB write the exact readtable code for you, which you can then save and reuse.
To handle missing data effectively, use the 'TreatAsEmpty' name-value pair. For example, if your spreadsheet uses the string "Missing" to denote empty cells, you can use readtable('file.xlsx', 'TreatAsEmpty', 'Missing'). This tells MATLAB to convert those specific strings into NaN (Not-a-Number), which is the standard way MATLAB handles missing numeric data, allowing you to use functions like rmmissing or fillmissing later.
If you are dealing with extremely large Excel files that slow down your system, consider converting the Excel file to a .csv (Comma Separated Values) format first. MATLAB can read .csv files significantly faster using readtable or readmatrix because it does not have to parse the complex XML structure of an .xlsx file.
Troubleshooting
If you encounter an error stating that the file cannot be found, first verify the spelling of the filename, including the extension. Then, type pwd in the Command Window to see your current directory. If the file is not in that folder, use the cd command to change directories or provide the full path to the file. Ensure there are no hidden file extensions (e.g., your file is actually named data.xlsx.xlsx because Windows hid the first extension).
If the data imports but the numbers are appearing as NaN or the columns are shifted, check for merged cells in your Excel sheet. Merged cells are the primary cause of alignment issues during import. Unmerge all cells and fill in the gaps with the appropriate values before re-importing.
When MATLAB reports a "Java heap space" error during a large Excel import, it means the memory allocated to the Java Virtual Machine (which MATLAB uses for some Excel interactions) is too low. You can increase this by going to Home > Preferences > MATLAB > General > Java Heap Memory and moving the slider to the right, then restarting MATLAB.
If you receive a "Permission Denied" error and the file is already closed, check if another user on your network has the file open or if a background process (like a crashed instance of Excel) is still holding the file. Restarting your computer or using the Task Manager to kill all Excel processes usually resolves this.
Frequently Asked Questions
Can I read only specific columns from an Excel file?
Yes, you can use the 'SelectedVariableNames' argument within readtable to specify exactly which columns you want to import by their header names, which saves memory and time.
What is the difference between readtable, readmatrix, and readcell?
readtable creates a table with headers; readmatrix creates a numeric array (ignoring text); readcell creates a cell array that can hold any mixture of data types without headers.
How do I handle Excel files with multiple header rows?
You can use the 'NumHeaderLines' argument to tell MATLAB how many rows to skip at the top of the file before it begins reading the data and headers.
Does MATLAB require Microsoft Excel to be installed on the computer?
No, for basic .xlsx and .xls files, MATLAB uses its own internal libraries to parse the files, so you do not need a licensed copy of Excel installed to read the data.
How can I import data from a password-protected Excel file?
MATLAB cannot natively read password-protected Excel files via readtable. You must first open the file in Excel, remove the password, and save it before importing it into MATLAB.