dlmwrite — Write numeric matrices to delimiter-separated text files in MATLAB and RunMat.
dlmwrite(filename, M) writes numeric matrix data to plain-text files using configurable delimiters. Precision, line-ending, and offset options follow MATLAB and RunMat legacy semantics.
Syntax
dlmwrite(filename, M)
dlmwrite(filename, M, delimiter, row, col)
dlmwrite(filename, M, name, optionValue)
dlmwrite(filename, M, args...)
bytesWritten = dlmwrite(filename, M)
bytesWritten = dlmwrite(filename, M, delimiter, row, col)
bytesWritten = dlmwrite(filename, M, name, optionValue)
bytesWritten = dlmwrite(filename, M, args...)Inputs
filename- Type
StringScalar- Required
- Yes
- Description
- Output file path.
M- Type
Any- Required
- Yes
- Description
- Numeric/logical matrix to write.
delimiter- Type
StringScalar- Required
- Yes
- Default
","- Description
- Delimiter token.
row- Type
IntegerScalar- Required
- Yes
- Default
0- Description
- Row offset before writing matrix rows.
col- Type
IntegerScalar- Required
- Yes
- Default
0- Description
- Column offset before writing matrix columns.
name- Type
StringScalar- Required
- Yes
- Description
- Option name.
optionValue- Type
Any- Required
- Yes
- Description
- Option value.
args...- Type
Any- Required
- Variadic
- Description
- Optional delimiter/offset/append and name-value options.
Returns
bytesWritten- Type
NumericScalar- Description
- Number of bytes written to the output file.
Errors
- When
- Argument sequence or name-value grammar is malformed.
- Message
dlmwrite: invalid argument configuration
- When
- Filename is missing, empty, or not a scalar string/char vector.
- Message
dlmwrite: invalid filename input
- When
- Option name or value is invalid.
- Message
dlmwrite: invalid option value
Data, formatting, offsets
Accepts real numeric or logical arrays up to two dimensions (trailing singleton dimensions are ignored). All eight integer classes serialize directly from authoritative storage at default precision, including uint64 values beyond flintmax. Logical values are converted to 0/1.
The default delimiter is a comma. Supply a character vector, string scalar, or control sequence ("\t", "\n", "\r") to change it. Delimiters must not be empty.
Positional syntax matches MATLAB: dlmwrite(filename, M, delimiter) and dlmwrite(filename, M, delimiter, row, col) provide quick overrides. Row/column offsets are zero-based and insert blank rows/columns filled with the delimiter before the numeric data.
Name-value pairs extend any syntax: '-append' appends to an existing file, 'delimiter' overrides the separator, 'precision' accepts either a scalar (significant digits) or a C-style printf format such as '%.6f', 'newline' chooses between 'pc' (CRLF), 'unix' (LF), or 'mac' (CR), and 'roffset'/'coffset' mirror the positional offsets. Typed integer offsets and precision counts are decoded exactly. Row and column additions are checked before file access, and layouts above 50,000,000 fields reject with a controlled size error.
Explicit precision intentionally enters the floating formatting domain; default integer formatting remains exact.
MATLAB documents complex numeric and numeric cell input and documents no output argument. RunMat currently rejects complex/cell data; requesting RunMat's byte-count output is a named extension.
Empty fields created by offsets are emitted as empty tokens separated by the delimiter, matching MATLAB's behaviour.
Files are opened in text mode. When appending, RunMat preserves the existing newline convention and honours offsets relative to the end of the file.
Paths beginning with ~ expand to the user's home directory before writing, matching other RunMat I/O builtins.
Filesystem and execution
The selected filesystem provider, relative working directory and advertised lease are captured before resident gather and retained through metadata, append inspection, write and flush. Host formatting is a fusion boundary. Partial bytes may remain after a write or cancellation failure. Finite complete-call memory evidence for gathered input and formatted rows remains a shared resource-admission requirement.
Formatting always runs on the host. Resident numeric input is downloaded only under the named RunMat extension; strict compatibility mode rejects it before provider readback or file creation. The output is never device-resident, and no device-kernel or fusion route is advertised.
The historical programs and captions below are preserved; the runnable gallery uses isolated deterministic fixtures with asserted file contents:
Historical example 1 (Writing a numeric matrix with the default comma delimiter):
A = [1 2 3; 4 5 6];
dlmwrite("scores.csv", A)
Historical example 2 (Using a semicolon delimiter and positional offsets):
B = magic(3);
dlmwrite("offset.txt", B, ";", 1, 2)
Historical example 3 (Appending data with explicit row and column offsets):
dlmwrite("log.txt", 1:3);
dlmwrite("log.txt", 10:12, "-append", "roffset", 1, "coffset", 1)
Historical example 4 (Controlling precision with significant digits):
vals = [12.34567, pi];
dlmwrite("precision3.csv", vals, "precision", 3)
Historical example 5 (Emitting fixed-point values with a printf-style format string):
dlmwrite("fixed.txt", rand(2, 2), "precision", "%.6f", "delimiter", "\t")
Historical example 6 (Writing resident data with Windows line endings):
G = gpuArray(single([1.5; 2.5; 3.5]));
dlmwrite("gpu_pc.txt", G, "newline", "pc")
Displayed output:
% Data is gathered from the GPU and written using CR/LF line endings.
Examples
Writing a numeric matrix with the default comma delimiter
A = [1 2 3;4 5 6];
dlmwrite('scores.csv',A);
M = dlmread('scores.csv')Using a semicolon delimiter and positional offsets
B = magic(3);
dlmwrite('offset.txt',B,';',1,2);
M = dlmread('offset.txt',';',1,2)Appending data with explicit row and column offsets
dlmwrite('log.txt',10:12,'-append','roffset',1,'coffset',1);
contents = fileread('log.txt')Controlling precision with significant digits
vals = [12.34567,pi];
dlmwrite('precision3.csv',vals,'precision',3);
M = dlmread('precision3.csv')Emitting fixed-point values with a printf-style format string
A = [1.25 2.5;3.75 4];
dlmwrite('fixed.txt',A,'precision','%.6f','delimiter','\\t');
contents = fileread('fixed.txt')Write Windows line endings
A = [1.5;2.5;3.5];
dlmwrite('pc.txt',A,'newline','pc');
contents = fileread('pc.txt')Writing resident data with Windows line endings
G = gpuArray(single([1.5;2.5;3.5]));
dlmwrite('gpu_pc.txt',G,'newline','pc');
contents = fileread('gpu_pc.txt')Using dlmwrite with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how dlmwrite changes the result.
Run a small dlmwrite example, explain the result, then change one input and compare the output.
FAQ
Which data types does dlmwrite support?⌄
Real numeric and logical arrays up to two dimensions. Use writematrix/writecell for text or heterogeneous data.
How does the '-append' flag interact with offsets?⌄
Offsets are applied relative to the end of the existing file. '-append','roffset',2 inserts two blank delimiter-filled rows before writing the new data.
What happens if I request both positional and name-value offsets?⌄
RunMat follows MATLAB by allowing both; the last specification wins. For clarity, prefer one style per call.
Can I combine '-append' with positional delimiter arguments?⌄
Yes. For example dlmwrite(fname, M, ';', '-append') uses the semicolon delimiter and appends to the file.
Does 'precision', N control decimal places or significant digits?⌄
It controls significant digits (like MATLAB's %.*g). For fixed decimal places, pass a printf-style format such as '%.6f'.
Which line endings are supported?⌄
'newline','pc' emits \r\n (Windows). 'newline','unix' emits \n, and 'newline','mac' emits \r. The default matches the current platform.
How are NaN and Inf values written?⌄
They are emitted verbatim as NaN, Inf, or -Inf, independent of the precision setting, matching MATLAB.
How are offsets represented in the file?⌄
roffset produces blank delimiter-separated rows, while coffset inserts empty fields before each data row. Downstream tools will see empty strings for the offset cells.
Does dlmwrite normalise path separators?⌄
No. Paths are passed directly to the OS after optional ~ expansion, exactly like MATLAB.
Should new code use dlmwrite?⌄
Prefer writematrix for new code. Use dlmwrite only when maintaining legacy scripts that rely on its exact output.
Related Io functions
Tabular
arrayDatastore · csvread · csvwrite · detectImportOptions · dlmread · fileDatastore · getvaropts · parquetDatastore · parquetinfo · parquetread · readcell · readmatrix · 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 dlmwrite is executed, line by line, in Rust.
- View the source for dlmwrite 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.