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
filename- Type
StringScalar- Required
- Yes
- Description
- Delimited text file path.
options- Type
Any- Required
- Yes
- Description
- Options struct containing readmatrix name/value fields.
name- Type
StringScalar- Required
- Yes
- Description
- Option name.
optionValue- Type
Any- Required
- Yes
- Description
- Value for the preceding option name.
nameValuePairs...- Type
Any- Required
- Variadic
- Description
- Name-value option pairs.
Returns
M- Type
Any- Description
- Imported matrix output (numeric/logical, and may preserve gpuArray residency with Like).
Errors
- When
- Argument list is malformed for readmatrix call forms.
- Message
readmatrix: invalid argument configuration
- When
- Option name is not a scalar string/char vector.
- Message
readmatrix: invalid option name
- When
- A provided option value is invalid.
- Message
readmatrix: invalid option value
Behavior and forms
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 NaN by default; specify 'EmptyValue', value to inject a replacement scalar, or 'TreatAsMissing', tokens to mark additional strings as missing.
'OutputType' supports double, single, logical, and all eight native integer classes. Integer imports parse decimal fields directly into authoritative storage, preserve int64 and uint64 values above flintmax, and saturate values that exceed the selected class; logical output maps nonzero values, including NaN, to true.
'Like', prototype is a RunMat-only extension. It matches host class or uploads through the exact provider that owns a resident prototype; upload failure, wrong ownership, wrong device, or wrong dtype is an error rather than a silent host fallback.
Typed-integer range, header, size, and empty-value controls are RunMat-only extensions when the public datatype table excludes native integers. MATLAB compatibility mode rejects those forms before gathering or opening the file, while documented integer OutputType results remain available.
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.
This reader returns one output and accepts delimited text files; spreadsheet decoding and a delimiter second output are not implemented.
Historical result captions
Historical example 1 — Read Comma-Separated Values With Automatic Delimiter Detection: % Returns a numeric matrix containing the CSV data.
Historical example 2 — Skip Header Lines Before Reading Numeric Data: % The first two lines are skipped; the remaining numeric rows are returned.
Historical example 3 — Import Tab-Delimited Text By Specifying The Delimiter: % Numeric matrix representing the tab-delimited values.
Historical example 4 — Treat Custom Tokens As Missing Values: % Entries equal to "NA" or "missing" become NaN in the output matrix.
Historical example 5 — Use European Decimal And Thousands Separators: % Values like "1.234,56" are interpreted as 1234.56.
Historical example 6 — Replace Empty Numeric Fields With A Custom Value: % Blank entries become 0 instead of NaN.
Historical example 7 — Import A Specific Range Of Cells: % Returns only the rows and columns covered by the specified range.
Historical example 8 — Convert The Result To A Logical Matrix: % Non-zero entries (including NaN) become logical true, zero stays false.
Historical example 9 — Keep The Result On The GPU By Matching A Prototype: % The parsed matrix is uploaded to the same GPU device as the prototype.
Historical example 10 — Provide Direct Struct Controls: % Reads the file using the supplied options struct.
Execution and source ownership
The selected filesystem provider, working directory and advertised resource lease are captured before resident controls suspend. The same provider opens the file; parsing stays on the host and forms a fusion boundary. Like may explicitly restore the result to the prototype's exact provider.
The reader limits input files to 512 MiB and checks cancellation and filesystem liveness while scanning and converting rows. Decoded text and the resulting matrix can require more memory than the file size.
GPU Like example: proto = gpuArray.zeros(1); G = readmatrix("data/heavy.csv", 'Like', proto); assert(isa(G,'gpuArray')); assert(isequal(gather(G),[1 2;3 4])); uploads the parsed matrix to the prototype's provider. The gallery also checks the same Like option with a host prototype.
Examples
Read Comma-Separated Values With Automatic Delimiter Detection
M = readmatrix("data/scores.csv")
MSkip Header Lines Before Reading Numeric Data
M = readmatrix("data/sensor_log.txt", 'NumHeaderLines', 2)
MImport Tab-Delimited Text By Specifying The Delimiter
M = readmatrix("data/report.tsv", 'Delimiter', 'tab')
MTreat Custom Tokens As Missing Values
M = readmatrix("data/results.csv", 'TreatAsMissing', ["NA", "missing"])
MUse European Decimal And Thousands Separators
M = readmatrix("data/europe.csv", 'Delimiter', ';', 'DecimalSeparator', ',', 'ThousandsSeparator', '.')
MReplace Empty Numeric Fields With A Custom Value
M = readmatrix("data/with_blanks.csv", 'EmptyValue', 0)
MImport A Specific Range Of Cells
M = readmatrix("data/quarterly.csv", 'Range', 'B2:D5')
MConvert The Result To A Logical Matrix
flags = readmatrix("data/thresholds.csv", 'OutputType', 'logical')
flagsKeep 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)
GMatch a host single-precision prototype
proto = single(zeros(1));
M = readmatrix("data/heavy.csv", 'Like', proto)
MProvide Direct Struct Controls
opts = struct('Delimiter', ',', 'NumHeaderLines', 1);
M = readmatrix("data/measurements.csv", opts)
MUsing 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?⌄
Yes. Pass 'OutputType','single'. RunMat returns a native single-precision array.
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, modify its typed options object, 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);. Per-variable numeric controls can be set with setvaropts. RunMat also retains the earlier direct-struct control form for compatibility.
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
arrayDatastore · csvread · csvwrite · detectImportOptions · dlmread · dlmwrite · fileDatastore · getvaropts · parquetDatastore · parquetinfo · parquetread · readcell · readtable · readtimetable · setvaropts · setvartype · spreadsheetImportOptions · writecell · writematrix · writetable · writetimetable · xlsread · xlswrite
Repl Fs
addpath · cd · copyfile · delete · dir · exist · fileattrib · fileparts · filesep · fullfile · genpath · getenv · getpref · isenv · isfile · isfolder · ispref · ls · matlabroot · memmapfile · memmapfile.subsasgn · memmapfile.subsref · mkdir · movefile · open · opentoline · path · pathsep · pcode · pwd · readstruct · rehash · restoredefaultpath · rmdir · rmpath · run · savepath · setenv · setpref · system · tempdir · tempname · uigetdir · uigetfile · uiputfile · unsetenv · userpath · what · winqueryreg · xmlread · xmlwrite
Data
commit · data.copy · data.create · data.delete · data.exists · data.export · data.import · data.inspect · data.list · data.move · data.open · DataArray.chunk_shape · DataArray.codec · DataArray.dtype · DataArray.fill · DataArray.name · DataArray.rank · DataArray.read · DataArray.resize · DataArray.shape · DataArray.write · Dataset.array · Dataset.arrays · Dataset.attrs · Dataset.begin · Dataset.get_attr · Dataset.has_array · Dataset.id · Dataset.path · Dataset.refresh · Dataset.set_attr · Dataset.set_attrs · Dataset.snapshot · Dataset.version · DataTransaction.abort · DataTransaction.commit · DataTransaction.create_array · DataTransaction.delete_array · DataTransaction.fill · DataTransaction.id · DataTransaction.resize · DataTransaction.set_attr · DataTransaction.set_attrs · DataTransaction.status · DataTransaction.write
Filetext
fclose · feof · fgetl · fgets · fileread · filewrite · fopen · fprintf · fread · frewind · fwrite · readlines · writelines
Import
Json
Source you can read
Every RunMat function's source is public. 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 a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/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.