Back to Blog
Blogs 8 min read

How to Read CSV File in MATLAB: Modern Functions & Methods

Learn how to read CSV file in MATLAB with the latest recommended functions. This guide shows how to work with readtable, readmatrix, and readcell, and includes tips for handling errors and setting options for missing data.

Himanshu Garg
Himanshu Garg October 31, 2026 0 views
how to read csv file in matlab - How to Read CSV File in MATLAB: Modern Functions & Methods

Learn how to read CSV file in MATLAB with the latest recommended functions. This guide shows how to work with readtable, readmatrix, and readcell, and includes tips for handling errors and setting options for missing data.

Quick answer

To read a CSV file in MATLAB, use the newer functions instead of the old csvread command.

– If the file contains both text and numbers, load it with
`data = readtable("filename.csv")`.

– If the file has only numbers, load it with
`matrix = readmatrix("filename.csv")`.

– If the file is irregular or has mixed scalar fields, load it with
`cells = readcell("filename.csv")`.

You can also change how the file is imported, for example, how missing values are handled, by first creating import options with `detectImportOptions` and then adjusting them with `setvaropts` before you read the file.

Modern Methods for Importing CSV Data into MATLAB

Reading comma-separated value (CSV) files is a basic step in data analysis, control-systems work, and numerical simulation. When determining how to read CSV file in MATLAB, modern workflows rely on three primary functions introduced in MATLAB R2019a: readtable, readmatrix, and readcell. These functions replace older utilities and use a stronger parser that can deal with complex data layouts. MathWorks no longer recommends using legacy functions like csvread and dlmread for new code. The old functions are still available for backward compatibility, but they cannot automatically handle headers, mixed text and numeric columns, or missing values.

Picking the modern function that matches your data format avoids common runtime errors and cuts memory use in large simulations.

For a closely related example, see Application analysis of soil nail and cable support in deep excavations of loess regions under complex environmental conditions.

Choosing the Right MATLAB CSV Import Function

Select the modern MATLAB function that best matches your CSV file structure and desired output format.

Factor Engineering view Why it matters
Mixed text/numbers with headers readtable Returns a table object; preserves column names and data types.
Strictly numeric data readmatrix Returns a double matrix; efficient for homogeneous mathematical arrays.
Irregular rows or mixed scalar fields readcell Returns a cell array; useful when rows have varying data types.

Parsing Mixed Data Structures with readtable

The readtable function is the most versatile option for standard CSV files containing a mix of numeric data, text descriptions, and headers. It imports the file into a MATLAB table object, preserving variable names and data types. This is ideal for structured datasets where columns represent distinct variables and rows represent observations.
Let us assume a verifiable file named 'sensor_log.csv' exists in your MATLAB working directory with the following structure:
Timestamp,Temperature,Voltage,Status
2023-10-24 08:00:00,23.5,5.01,Active
2023-10-24 08:01:00,24.0,4.98,Active
2023-10-24 08:02:00,NaN,5.00,Warning
To read this file, use the following MATLAB syntax:

% Define the file path and import as a table
filePath = 'sensor_log.csv';
data = readtable(filePath);
% Access specific variables using dot notation
temperatures = data.Temperature;

This approach automatically detects the header row and assigns variable names accordingly, making it highly readable for downstream analysis. The resulting table also supports native datetime conversion for timestamp columns.

For a closely related example, see AutoML-Based Model Selection System for CSV Datasets.

Importing Pure Numeric Arrays with readmatrix

When your CSV file contains strictly numeric data without headers or text columns, readmatrix is the appropriate tool. It returns a standard MATLAB double-precision matrix. This is highly useful for importing raw sensor outputs, simulation trajectories, or mathematical matrices.
Let us assume a file named 'matrix_data.csv' containing only numeric values:
1.2,3.4,5.6
7.8,9.0,1.2
3.4,5.6,7.8
The corresponding MATLAB code to import this matrix is:

% Import numeric data directly into a double matrix
numericMatrix = readmatrix('matrix_data.csv');

While readmatrix is streamlined, it is a misconception that it is always the fastest parser or uses the least memory under all system conditions. For massive datasets, performance depends heavily on disk I/O, system RAM, and the specific structure of the file. If your numeric file contains a single header row, you can still use readmatrix by configuring it to skip the header line using the 'NumHeaderLines' parameter.

For a closely related example, see Optimization of Process Parameters for Advanced High-Strength Steel JSC980Y Automotive Part Using Finite Element Simulation and Deep Neural Network.

Diagnosing CSV Import Failures in MATLAB

Follow these diagnostic steps when modern MATLAB CSV functions return errors or unexpected data formats.

  1. 1File Not Found Error
    Verify the file path using isfile() or check the current MATLAB working directory.

    Use absolute paths to avoid directory resolution issues.

  2. 2All data in a single column
    Check the delimiter in the CSV file. Modify opts.Delimiter if it is a semicolon or tab.

    detectImportOptions can help identify the delimiter automatically.

  3. 3Numeric columns imported as text
    Look for non-numeric characters, such as currency symbols or custom missing value strings.

    Use setvaropts to register custom string patterns as missing values.

  4. 4Unexpected NaN values
    Configure TreatAsMissing and FillValue properties using setvaropts.

    Do not look for opts.FillValue directly; configure it per variable.

Handling Irregular or Mixed Scalar Fields with readcell

If a CSV file contains a highly irregular structure or a mix of scalar text and numeric fields that do not conform to a strict tabular format, readcell is an alternative. It imports the data into a MATLAB cell array, where each cell holds an individual scalar value (such as a single double, string, or datetime).

% Import the entire file into a cell array
cellData = readcell('mixed_data.csv');

It is important to understand that readcell accepts mixed scalar fields; it does not parse nested cell arrays directly from a CSV file. Furthermore, readcell does not guarantee that highly irregular files with missing delimiters or misaligned rows will parse correctly without additional manual indexing or pre-processing of the raw text. Cell arrays also require more memory than matrices or tables, so readcell should be reserved for scenarios where structural irregularities prevent the use of readtable.

Handling Missing Values with setvaropts

Real-world data often contains missing values, represented in CSV files by empty spaces, placeholders like 'N/A', or specific numeric codes. To handle these missing values during import, do not search for a global 'opts.FillValue' property, as that does not exist in standard MATLAB import options. Instead, you must configure per-variable options using detectImportOptions and setvaropts.

% Detect the default import options for the file
opts = detectImportOptions('sensor_log.csv');
% Set specific fill values for the 'Temperature' variable
opts = setvaropts(opts, 'Temperature', 'TreatAsMissing', 'NaN', 'FillValue', 0.0);
% Import the table using the modified options
data = readtable('sensor_log.csv', opts);

This method ensures that missing entries in specific columns are filled with context-appropriate defaults (such as zero or a column mean) during the initial parsing phase, preventing downstream calculations from failing due to unexpected NaN values.

Best Practices for Modern MATLAB CSV Parsing

Keep these essential rules in mind to write clean, maintainable, and high-performance import scripts.

Avoid Legacy Functions

Do not use csvread or dlmread. They are not recommended by MathWorks and lack modern parser optimizations.

Modern functions are safer and more flexible.

Programmatic Control

Always use detectImportOptions to inspect and modify schema properties before reading large files.

This prevents memory wastage and type mismatch errors.

Missing Values

Configure missing fill values on a per-variable basis using setvaropts instead of relying on global parameters.

Provides granular control over data cleaning.

Data Validation

Always run head() or summary() on imported tables to verify that column data types were inferred correctly.

Catches parsing errors early in the pipeline.

Troubleshooting and Validating CSV Imports

When a CSV import fails, the root cause is typically a mismatch between the file structure and the expected parser options. Common issues include incorrect character encoding, unexpected delimiters (such as semicolons instead of commas), or non-numeric characters in a file read by readmatrix.

% Specify a custom delimiter and character encoding
opts = detectImportOptions('european_data.csv');
opts.Delimiter = ';';
opts.CharacterEncoding = 'UTF-8';
% Read the file with corrected options
data = readtable('european_data.csv', opts);

To validate that the import succeeded without data corruption, inspect the first few rows using the head() function or check the data types of each variable using the summary() function. This step prevents silent type conversions, such as a column of numbers being imported as text because of a single misplaced non-numeric character.

Key takeaways

  • Modern MATLAB workflows should use readtable, readmatrix, or readcell instead of legacy csvread or dlmread.
  • The readtable function is best for structured datasets containing mixed data types and column headers.
  • Use readmatrix for homogeneous numeric arrays, but do not assume it is always the fastest parser for every edge case.
  • For mixed scalar fields or irregular files, readcell imports data into a cell array, though it does not guarantee parsing of malformed files.
  • Handle missing values programmatically by combining detectImportOptions with setvaropts on specific variables.

Questions engineers often ask

Why does MATLAB say csvread is not recommended?

MathWorks no longer recommends csvread because it cannot handle modern data types, column headers, or mixed text-numeric data. New functions such as readtable and readmatrix provide better type detection, use memory more efficiently, and give strong options for dealing with missing values.

How do I read a CSV file with mixed text and numbers in MATLAB?

To read a CSV file containing mixed text and numbers, use 'data = readtable("filename.csv")'. This imports the data into a MATLAB table, automatically detecting headers and assigning appropriate data types (such as double, string, or datetime) to each column.

Can I use readmatrix if my CSV file has a header row?

Yes, you can use readmatrix with a header row by specifying the 'NumHeaderLines' parameter. For example, 'matrix = readmatrix("filename.csv", "NumHeaderLines", 1)' skips the first row and imports the remaining numeric data.

How do I specify custom missing value placeholders during import?

If you want to define your own missing-value symbols, first call detectImportOptions to create an options object. Then use setvaropts to tell MATLAB which strings (for example 'N/A' or 'NULL') should be treated as missing, and set the fill value you want for that variable.

Continue learning: how to read csv file in matlab

Explore more software and data engineering guides on Fried Engineers.

Chat with Fried Engineers