readmatrix — Import numeric data from delimited text files with MATLAB-compatible readmatrix behavior.
readmatrix(filename) reads numeric data from text or delimited files and returns a dense matrix. It follows MATLAB defaults for delimiter detection, import ranges, header skipping, and missing-value handling.
Syntax
M = readmatrix(filename)
M = readmatrix(filename, options)
M = readmatrix(filename, name, optionValue)
M = readmatrix(filename, options, name, optionValue)
M = readmatrix(filename, nameValuePairs...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
filename | StringScalar | Yes | — | Delimited text file path. |
options | Any | Yes | — | Options struct containing readmatrix name/value fields. |
name | StringScalar | Yes | — | Option name. |
optionValue | Any | Yes | — | Value for the preceding option name. |
nameValuePairs... | Any | Variadic | — | Name-value option pairs. |
Returns
| Name | Type | Description |
|---|---|---|
M | Any | Imported matrix output (numeric/logical, and may preserve gpuArray residency with Like). |
Errors
| Identifier | When | Message |
|---|---|---|
| — | Argument list is malformed for readmatrix call forms. | readmatrix: invalid argument configuration |
| — | Option name is not a scalar string/char vector. | readmatrix: invalid option name |
| — | A provided option value is invalid. | readmatrix: invalid option value |
| — | Range specification is malformed or semantically invalid. | readmatrix: invalid range |
| — | Filename argument is not a scalar string/char vector. | readmatrix: invalid filename input |
| — | Filename resolves to an empty path. | readmatrix: filename must not be empty |
| — | Input file cannot be opened. | readmatrix: unable to read file |
| — | Input file cannot be read. | readmatrix: failed to read file |
| — | A token cannot be parsed as numeric in the selected import region. | readmatrix: nonnumeric token encountered |
| — | OutputType/Like output coercion configuration is invalid. | readmatrix: invalid output type configuration |
| — | Internal tensor/logical output materialization fails. | readmatrix: unable to construct output matrix |
How readmatrix works
- Accepts character vectors or string scalars for the file name. String arrays must contain exactly one element.
- Supports option structs (from
detectImportOptions) as well as name/value arguments such as'Delimiter','NumHeaderLines','TreatAsMissing','DecimalSeparator','ThousandsSeparator', and'EmptyValue'. - Accepts
'Range'as either an Excel-style address ("B2:E10") or a numeric vector[rowStart colStart rowEnd colEnd]to slice the imported data. - Automatically detects comma, tab, semicolon, pipe, or whitespace delimiters when none are specified. Detection is based on the first few non-empty data lines.
- Parses numeric values using MATLAB-compatible rules, recognising
NaN,Inf,-Inf, and locale-specific decimal/thousands separators. - Treats empty fields as
NaNby default; specify'EmptyValue', valueto inject a replacement scalar, or'TreatAsMissing', tokensto mark additional strings as missing. 'OutputType','logical'coalesces non-zero numeric values (includingNaN) to logical true, mirroring MATLAB's casting behaviour.'Like', prototypematches the output class and residency of an existing array. Supplying a GPU tensor keeps the parsed matrix on the device when an acceleration provider is active.- Tolerates ragged rows by padding trailing elements with the configured empty value (default
NaN). - Raises descriptive errors when the file cannot be read or when a field cannot be parsed as a numeric value.
Does RunMat run readmatrix on the GPU?
readmatrix always executes on the host CPU. If the file name or option arguments are GPU-resident scalars, RunMat gathers them automatically before accessing the filesystem. The resulting matrix is created in host memory unless you pass 'Like', gpuPrototype, in which case the parsed tensor is uploaded to the same provider so subsequent operations remain on the device. Acceleration providers do not need bespoke hooks for this builtin.
Examples
Read Comma-Separated Values With Automatic Delimiter Detection
M = readmatrix("data/scores.csv")Expected output:
% Returns a numeric matrix containing the CSV data.Skip Header Lines Before Reading Numeric Data
M = readmatrix("data/sensor_log.txt", 'NumHeaderLines', 2)Expected output:
% The first two lines are skipped; the remaining numeric rows are returned.Import Tab-Delimited Text By Specifying The Delimiter
M = readmatrix("data/report.tsv", 'Delimiter', 'tab')Expected output:
% Numeric matrix representing the tab-delimited values.Treat Custom Tokens As Missing Values
M = readmatrix("data/results.csv", 'TreatAsMissing', ["NA", "missing"])Expected output:
% Entries equal to "NA" or "missing" become NaN in the output matrix.Use European Decimal And Thousands Separators
M = readmatrix("data/europe.csv", 'Delimiter', ';', 'DecimalSeparator', ',', 'ThousandsSeparator', '.')Expected output:
% Values like "1.234,56" are interpreted as 1234.56.Replace Empty Numeric Fields With A Custom Value
M = readmatrix("data/with_blanks.csv", 'EmptyValue', 0)Expected output:
% Blank entries become 0 instead of NaN.Import A Specific Range Of Cells
M = readmatrix("data/quarterly.csv", 'Range', 'B2:D5')Expected output:
% Returns only the rows and columns covered by the specified range.Convert The Result To A Logical Matrix
flags = readmatrix("data/thresholds.csv", 'OutputType', 'logical')Expected output:
% Non-zero entries (including NaN) become logical true, zero stays false.Keep The Result On The GPU By Matching A Prototype
proto = gpuArray.zeros(1); % simple prototype to establish residency
G = readmatrix("data/heavy.csv", 'Like', proto)Expected output:
% The parsed matrix is uploaded to the same GPU device as the prototype.Provide Options Using A Struct From detectImportOptions
opts = struct('Delimiter', ',', 'NumHeaderLines', 1);
M = readmatrix("data/measurements.csv", opts)Expected output:
% Reads the file using the supplied options struct.Using readmatrix with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how readmatrix changes the result.
Run a small readmatrix example, explain the result, then change one input and compare the output.
FAQ
What file encodings does readmatrix support?⌄
The builtin reads UTF-8 text files by default and ignores a leading UTF-8 byte-order mark automatically. Use the 'Encoding' name-value option or an options struct field to read supported non-UTF-8 text encodings such as 'windows-1252'.
Does readmatrix support Excel or binary files?⌄
This implementation focuses on delimited text files. For MAT-files use load, and for spreadsheets use the readtable / readcell family (planned).
How are missing values represented?⌄
Empty fields become NaN unless 'EmptyValue' is supplied. Additional tokens can be marked missing with 'TreatAsMissing', which also converts them to NaN.
What happens when rows have different numbers of columns?⌄
RunMat pads short rows with the empty value (default NaN) so the output remains rectangular.
Can I import only part of the file?⌄
Yes. Pass 'Range', 'B3:F20' (Excel-style addresses) or 'Range', [3 2 10 6] (row/column indices) to slice the data before it is materialised. Rows or columns outside the range are ignored entirely.
Are comment lines supported?⌄
Lines that are entirely blank are ignored. Use 'NumHeaderLines' to skip introductory text or call detectImportOptions for more control.
How do I read files stored on the GPU?⌄
File paths are always gathered to the CPU before reading. By default the parsed matrix is created on the host; supply 'Like', gpuArray.zeros(1) (or any GPU prototype) to upload the result automatically, or call gpuArray afterwards to move it manually.
Can I request single-precision output?⌄
readmatrix currently returns double-precision arrays, matching MATLAB defaults. Cast the result with single(...) when you need single precision.
How are delimiters detected automatically?⌄
The builtin inspects the first few non-empty data lines and chooses the candidate delimiter (comma, tab, semicolon, pipe, or whitespace) that produces the most columns consistently. Explicit 'Delimiter' settings override detection.
How are thousands separators handled?⌄
Specify 'ThousandsSeparator' to strip that character before parsing, e.g. '.' for European locales. The thousands and decimal separators must be different.
Does readmatrix modify the current directory?⌄
No. Relative paths are resolved against the current working directory, exactly like MATLAB.
What does readmatrix do in MATLAB?⌄
readmatrix(filename) reads numeric data from a text file (CSV, TSV, etc.) and returns it as a matrix. Non-numeric values are replaced with NaN.
How is readmatrix different from csvread?⌄
readmatrix is the modern replacement for csvread. It auto-detects delimiters, handles headers, and supports more file formats. csvread only handles comma-separated files with numeric data.
Can readmatrix skip header rows?⌄
Yes. Use the 'NumHeaderLines' option: readmatrix('file.csv', 'NumHeaderLines', 1) skips the first row. RunMat supports this same option.
How do I customise import options for readmatrix with detectImportOptions?⌄
— Call detectImportOptions first, tweak the returned struct, then pass it to readmatrix as the second argument. For example: opts = detectImportOptions('data.csv'); opts.NumHeaderLines = 1; opts.Delimiter = ','; A = readmatrix('data.csv', opts);. This is the MATLAB-recommended workflow when the file needs more than a couple of overrides, and RunMat accepts the same option struct directly.
How do I read a UTF-8 CSV file that starts with a byte-order mark?⌄
— readmatrix reads UTF-8 by default and silently strips a leading UTF-8 BOM (EF BB BF), so no extra option is needed. You can also make the encoding explicit with readmatrix('data.csv', 'Encoding', 'UTF-8'), or supply another supported text encoding such as readmatrix('legacy.csv', 'Encoding', 'windows-1252').
Which MATLAB release introduced readmatrix?⌄
— MATLAB introduced readmatrix in R2019a as the modern replacement for csvread/dlmread. RunMat supports it today with no release gate, so you can call readmatrix regardless of the MATLAB version you normally target.
Related Io functions
Tabular
csvread · csvwrite · detectImportOptions · dlmread · dlmwrite · spreadsheetImportOptions · writecell · writematrix · xlsread
Repl Fs
addpath · cd · copyfile · delete · dir · exist · fullfile · genpath · getenv · ls · mkdir · movefile · path · pwd · rmdir · rmpath · run · savepath · setenv · tempdir · tempname · uigetfile · uiputfile
Filetext
fclose · feof · fgetl · fgets · fileread · filewrite · fopen · fprintf · fread · frewind · fwrite
Import
Json
Archive
Http
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how readmatrix is executed, line by line, in Rust.
- View the source for readmatrix in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.