Curious Minds

Clear answers to science and history questions

How to Import a File into MATLAB

· 7 min read · Science

To import a file into MATLAB, you tell MATLAB where the file is, then use the function that matches its format: readmatrix, readtable or readcell for delimited text and spreadsheets, load or importdata for simple numeric files, readtable with a Sheet name for Excel workbooks, imread for images, audioread for sound files, and jsondecode or xmlread for structured text. The key habit that saves the most time is putting the file in the current folder (or adding its folder to the path) and capturing the result in a variable, so you can inspect it before writing more code.

What You'll Need

  • A working MATLAB installation (the import functions readtable, readmatrix, readcell and imread are standard in modern releases; very old versions may lack the read* family).
  • The file itself, saved somewhere you can find, ideally in the folder shown in MATLAB's Current Folder panel.
  • Knowing the file's format and, for text files, the delimiter (comma, tab, semicolon, space) and whether the first row contains variable names.
  • For Excel, audio, image or HDF5 files: the relevant toolbox or built-in support. Basic Excel reading is built in; some formats need an add-on.
  • A text editor or the MATLAB Import Tool if the file is messy and you want to see its layout first.

Step-by-Step

  1. Find the file's full path. In MATLAB, use the Current Folder browser on the left to navigate to the folder holding your file. You can also type pwd to see the current folder and dir to list files in it. Confirm the exact name and extension with dir *.csv or whatever pattern matches.
  2. Put MATLAB in the right place. Either move the file into the current folder, use cd to change into the file's folder, or add that folder to the search path with addpath('C:\path\to\folder'). Windows paths in MATLAB use either forward slashes ('C:/data/file.csv') or doubled backslashes ('C:\\data\\file.csv').
  3. Peek at the file before importing. For text files, open the file in a text editor or use type file.csv to see the first lines. Check whether there is a header row, whether the delimiter is a comma or something else, and whether numbers use dots or commas as decimal separators. This single step prevents most import errors.
  4. Choose the right function. Use readtable when the file has mixed text and numbers and you want named columns; use readmatrix when the file is purely numeric and you want a plain matrix; use readcell when data types are mixed and you want raw cells. For Excel, readtable and readmatrix also work.
  5. Run a basic import. For example: data = readtable('measurements.csv'); or M = readmatrix('numbers.csv');. Capture the output in a variable; don't run the function without an output, or the data is only displayed and then lost.
  6. Handle a missing header. If your file has no header row and you use readtable, MATLAB may treat the first data row as variable names. Fix it with readtable('file.csv','ReadVariableNames',false) or check the result with head(data) and size(data).
  7. Specify the delimiter or options when needed. Tab-separated files: readtable('file.txt','Delimiter','\t'). Skip comment lines with 'CommentStyle','#'. Set the decimal separator with 'DecimalSeparator',',' for European-style files. Use detectImportOptions('file.csv') to let MATLAB propose options, then adjust and pass them to readtable.
  8. Import a specific Excel sheet or range. Use readtable('book.xlsx','Sheet','Sheet2') to pick a sheet, and 'Range','B2:D50' to read a block. To discover what a workbook contains, use sheetnames('book.xlsx') before importing.
  9. Verify the result. Check the size, the first few rows and the data types: size(data), head(data), class(data), and for a table, data.Properties.VariableNames. Look for unexpected NaN or text values where numbers should be; that signals a parsing problem.
  10. Save the imported data if you'll reuse it. Save as a MATLAB file with save('mydata.mat','data') so future sessions can load it instantly with load('mydata.mat'), avoiding repeated slow parsing of large text files.

Common Mistakes

  • Assuming the file is on the path. MATLAB only sees files in the current folder or on the search path. "File not found" almost always means the folder is wrong, not that the file is missing.
  • Forgetting to assign the output. Typing readtable('file.csv') without data = displays a preview but leaves nothing in the workspace.
  • Using backslashes unescaped. A single backslash in a character vector can create escape sequences; use forward slashes or double the backslashes.
  • Ignoring a header row mismatch. Treating headers as data, or data as headers, shifts every column and corrupts the analysis.
  • Confusing decimal separators. A file using commas for decimals and semicolons for delimiters will parse wrongly unless you set both options.
  • Importing a huge file with the wrong function. Reading a table into a matrix when it contains text produces conversion errors or silently dropped text.
  • Not closing the Excel file. On some systems, importing a workbook that is open in Excel can fail or read stale data.

Tips

  • Use the Import Tool (uiimport or the Import Data button in the Home tab) to interactively preview a file, then generate the code MATLAB used; that code is a reliable starting point.
  • Use detectImportOptions and inspect the returned object with disp; you can edit properties like VariableNames and DataRange before importing.
  • Prefer readtable for real-world data: names stay attached to columns, and mixed types are handled gracefully.
  • For repeated imports of the same kind of file, store the options object once and reuse it; this keeps imports consistent and fast.
  • For large files, specify only the columns you need with 'SelectedVariableNames' or a range to reduce memory use.
  • Keep the raw file untouched and do cleaning in code, so the import remains reproducible.

Troubleshooting

"Unrecognized function or variable" or "File not found": Verify the current folder with pwd, list files with dir, and check the extension. Move the file into the current folder or add its folder with addpath.

Data appears as one column: The delimiter is wrong. Check the file in a text editor and specify 'Delimiter', or use detectImportOptions to let MATLAB infer it.

Numbers come in as text: The column likely contains stray characters, a currency symbol or a different decimal separator. Inspect the raw file and set 'DecimalSeparator' or clean the column after import with str2double.

Excel import fails or returns the wrong sheet: Confirm the sheet name with sheetnames, check for merged cells and blank leading rows, and close the workbook in Excel. Specify 'Range' if the data does not start at cell A1.

Text garbled or accented characters wrong: The file encoding does not match. Specify 'Encoding','UTF-8' where supported, or save the file as UTF-8 from its source program.

Image or audio import not recognized: The format may need a specific reader; check that the file is a supported type and, for special formats, that the required toolbox is installed with ver.

Out of memory on a large file: Import only needed columns and rows via options, read in chunks, or convert the file to a more efficient format such as MAT or binary first.

Frequently Asked Questions

What is the difference between readtable, readmatrix and readcell?

readtable returns a table with named variables and mixed types, readmatrix returns a numeric matrix and fails or skips non-numeric content, and readcell returns a cell array preserving raw values.

How do I import a CSV file with a header row?

Use data = readtable('file.csv'). MATLAB treats the first row as variable names by default, which you can verify with data.Properties.VariableNames.

Can MATLAB import Excel files without a toolbox?

Yes for common workbook formats: readtable, readmatrix and readcell read Excel files directly in modern releases. Some legacy formats or advanced features may need extra support.

How do I import only part of a file?

Use 'Range' for spreadsheets or 'DataRange' and 'SelectedVariableNames' in an import options object for text files, so only the rows and columns you need are read.

Why does MATLAB say the file does not exist when I can see it?

MATLAB searches only the current folder and the path. The file is probably in another folder, so change the folder with cd or add it with addpath.

How do I load data I saved earlier in MATLAB?

Use load('mydata.mat'). This restores the saved variables into the workspace without re-parsing the original text or spreadsheet file.

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions