save — Save workspace values to a Level-5 MAT-file.
save(filename) writes the selected caller workspace to an uncompressed Level-5 MAT-file. Variable names, string arrays of names, -struct, -regexp, and -append choose what is written. The MATLAB-compatible form is a zero-output statement; capturing the double-zero success status is a RunMat extension.
Syntax
status = save()
status = save(filename)
status = save(filename, varName1, varName2, ...)
status = save(filename, '-struct', structVar, field1, ...)
status = save(filename, '-regexp', pattern1, ...)
save(option, value, ...)Inputs
filename- Type
StringScalar- Required
- Yes
- Default
"matlab.mat"- Description
- Level-5 MAT-file path.
varName- Type
StringScalar- Required
- Variadic
- Description
- Whole variable names.
option- Type
StringScalar- Required
- Yes
- Description
- Supported MAT selection or save option.
pattern- Type
StringScalar- Required
- Variadic
- Description
- Regular-expression patterns.
Returns
status- Type
NumericScalar- Description
- Double zero on success.
Errors
RunMat:save:InvalidArgument- When
- Inputs are not a supported save form.
- Message
save: invalid argument
RunMat:save:InvalidOption- When
- A save option or value is invalid.
- Message
save: invalid option
RunMat:save:Selection- When
- A workspace variable or field cannot be resolved.
- Message
save: variable selection failed
Paths and selection
Bare save() writes matlab.mat, or RUNMAT_SAVE_DEFAULT_PATH when that environment override is set. Paths without an extension gain .mat; parent directories must exist. Explicit names select workspace variables. -struct writes selected fields as individual variables, and -regexp selects matching workspace names. Missing names, unmatched patterns, and malformed options reject with typed errors.
-append reads an existing Level-5 file, merges the new entries by name, and writes a refreshed file. A new value replaces an existing value of the same name. ASCII/text format switches such as -ascii and -double are not accepted.
Values
Dense real/complex single and double arrays; all eight signed/unsigned integer classes; logical, character, string, cell, struct, and real sparse arrays retain their available shapes and storage semantics. RunMat writes typed Level-5 object records and may invoke registered saveobj hooks. Function handles and opaque graphics handles are unsupported and raise errors.
Resident array values are gathered from their owning provider before encoding. The MAT file holds host bytes; saving does not mutate the original resident value. Large arrays, append, object callbacks, and full-file encoding may require substantial host memory.
Execution
The selected filesystem provider and relative path are captured before the file operation. Writes replace the path through that provider; MAT encoding does not create a device kernel. File writing is not a multi-file transaction and an operational error is not retried as a different route.
Examples
Save the entire workspace
x = 42;
y = magic(3);
save('session.mat')Save selected variables
a = [1 2 3];
b = eye(2);
c = 'ignore me';
save('selection.mat', 'a', 'b')Save struct fields as variables
x = 1:5;
y = [5 4 3 2 1];
opts = struct('output', y, 'answer', x);
save('opts.mat', '-struct', 'opts')Select names by regular expression
result_acc = 1:3;
result_tmp = 4:6;
scratch = pi;
save('filtered.mat', '-regexp', '^result_', 'tmp$')Append another variable
x = 7;
save('append.mat', 'x');
y = 2*x;
save('append.mat', 'y', '-append')Select names with a string array
result_acc = 5;
scratch = 9;
names = ["result_acc", "scratch"];
save('mixed.mat', names)Save a resident array
G = gpuArray(magic(3));
save('gpu.mat', 'G')Reject a missing workspace name
save('bad.mat', 'missing')Using save with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how save changes the result.
Run a small save example, explain the result, then change one input and compare the output.
FAQ
Which MAT-file version is generated?⌄
Uncompressed Level-5 MAT files. Dense available numeric classes, exact integers, and real sparse matrices use Level-5 class tags; HDF5-backed v7.3 output is not supported.
Is -append supported?⌄
Yes for supported Level-5 content. The existing file is decoded, entries are merged by name, and a new Level-5 file is written. A duplicate name is replaced by the new value.
Do -ascii or -double work?⌄
No. The current writer uses the Level-5 MAT format only.
Are objects or function handles saved?⌄
RunMat typed Level-5 object records and registered saveobj hooks are supported. Function handles are rejected.
Does save return a value?⌄
The MATLAB-compatible call is a zero-output statement. With RunMat extensions enabled, one captured output is double zero on success.
How do I change the bare-save filename?⌄
Set RUNMAT_SAVE_DEFAULT_PATH. With no explicit filename, save uses that path instead of matlab.mat.
Are parent folders created?⌄
No. The parent folder must already exist, or the filesystem provider returns an error.
Related Io functions
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
Tabular
arrayDatastore · csvread · csvwrite · detectImportOptions · dlmread · dlmwrite · fileDatastore · getvaropts · parquetDatastore · parquetinfo · parquetread · readcell · readmatrix · readtable · readtimetable · setvaropts · setvartype · spreadsheetImportOptions · writecell · writematrix · writetable · writetimetable · xlsread · xlswrite
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 save is executed, line by line, in Rust.
- View the source for save 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.