save — Persist variables from the current workspace to a MATLAB-compatible MAT-file.
save writes variables from the current workspace to a MAT-file on disk. It supports MATLAB-compatible variable selection, struct-field extraction, and option handling such as '-struct' and '-regexp'.
Syntax
status = save()
status = save(filename)
status = save(filename, varName1, varName2, ...)
status = save(filename, "-struct", structVar, field1, ...)
status = save(filename, "-regexp", pattern1, ...)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
filename | StringScalar | Yes | "matlab.mat" | MAT-file output path. |
varName | StringScalar | Variadic | — | Workspace variable names to persist. |
filename | StringScalar | No | "matlab.mat" | MAT-file output path. |
option | StringScalar | Yes | "-struct" | Struct field export option. |
structVar | StringScalar | Yes | — | Workspace struct variable name. |
option | StringScalar | Yes | "-regexp" | Regex selection option. |
pattern | StringScalar | Variadic | — | Regex patterns matched against workspace variable names. |
Returns
| Name | Type | Description |
|---|---|---|
status | NumericScalar | Zero status code on success. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:save:InvalidArgument | Arguments do not match supported save invocation forms. | save: invalid argument |
RunMat:save:InvalidOption | Option token or option value is invalid. | save: invalid option |
RunMat:save:Selection | Requested variables or struct fields cannot be resolved. | save: variable selection failed |
RunMat:save:Filename | Filename is invalid or cannot be normalized. | save: invalid filename |
RunMat:save:Io | MAT-file cannot be written or finalized. | save: MAT-file I/O failure |
RunMat:save:Unsupported | Unsupported save mode or value type is requested. | save: unsupported operation |
RunMat:save:Workspace | Workspace state is unavailable. | save: workspace state unavailable |
How save works
savewith no arguments writes every variable from the caller workspace tomatlab.matin the current working directory. SetRUNMAT_SAVE_DEFAULT_PATHto override the default target when no filename is supplied.save filenamewrites all workspace variables tofilename. If the supplied name has no extension,.matis added automatically. Paths are resolved relative to the current directory, and parent folders must already exist.save(filename, 'A', 'B')writes only the listed variables. String arrays or cell arrays of character vectors are accepted to specify multiple names.save(filename, '-struct', 'S')saves each field of structSas a separate variable. Provide additional field names ('field1','field2') to restrict the set.save filename -regexp '^foo' 'bar$'saves every variable whose name matches any of the supplied regular expressions.- Existing files are overwritten unless
-appendis specified. With-append, RunMat reads the existing supported MAT variables, merges in the newly selected variables, and rewrites the file so newer variables replace older variables with the same name. - Numeric/text format flags outside the MAT-file path (for example
-ascii,-double,-v6,-v7.3) are not supported yet and report descriptive option errors. - Unsupported types (function handles, objects, opaque graphics handles) raise descriptive errors. Numeric, logical, character, string, cell, scalar struct, and real sparse data are stored using MATLAB Level-5 MAT-file layout.
savereturns0so scripts can treat it as a statement, matching MATLAB's void behaviour.
Does RunMat run save on the GPU?
save acts as a residency sink. Before serialising, RunMat gathers any GPU-resident tensors through the active acceleration provider so the MAT-file contains host data. Fusion groups terminate at this builtin and providers do not require custom hooks.
GPU memory and residency
No manual action is required. save gathers gpuArray inputs automatically before writing the MAT-file. This matches MATLAB's behaviour when gpuArray variables are passed to save.
Examples
Save the entire workspace
x = 42;
y = magic(3);
save('session.mat')Save selected variables only
a = rand(1, 3);
b = eye(2);
c = "ignore me";
save('selection.mat', 'a', 'b')Save struct fields as individual variables
x = 1:5;
y = rand(1, 5);
opts = struct('output', y, 'answer', x);
save('opts.mat', '-struct', 'opts')Select variables by regular expression
result_acc = 1:3;
result_tmp = 4:6;
scratch = pi;
save('filtered.mat', '-regexp', '^result_', 'tmp$')Append variables to an existing MAT-file
save('session.mat', 'x')
y = 2*x;
save('session.mat', 'y', '-append')Save multiple names using a string array
names = ["result_acc", "scratch"];
save('mixed.mat', names)Save GPU arrays without manual gather
G = gpuArray(magic(3));
save('gpu.mat', 'G')Error when a variable is missing
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?⌄
RunMat writes uncompressed Level-5 (MATLAB 5.0) MAT-files, compatible with MATLAB R2006b and later as well as NumPy/Scipy readers. Numeric arrays preserve RunMat's available numeric classes (double, single, uint8, and uint16 tensors plus integer scalars), and real sparse matrices use standard mxSPARSE storage.
Is -append supported?⌄
Yes for supported MAT-file content. RunMat decodes the existing MAT-file, merges the selected variables, and writes a fresh Level-5 MAT-file. If a variable name already exists, the new value replaces the previous value, matching MATLAB's practical append workflow.
Do text options like -ascii or -double work?⌄
These legacy text/binary format switches are not supported. RunMat favours MATLAB's default MAT-file format.
Are objects or function handles saved?⌄
No. RunMat matches MATLAB by raising an error when unsupported types are encountered.
Does save return a value?⌄
Yes. The builtin returns 0, which MATLAB treats as an empty output, so scripts can ignore the return value just as they do in MATLAB.
How do I change the default filename used by bare save?⌄
Set the environment variable RUNMAT_SAVE_DEFAULT_PATH before launching RunMat. When save is called without explicit filename arguments, the builtin writes to that path instead of matlab.mat.
Does save create parent directories automatically?⌄
No. Parent folders must already exist; otherwise the builtin raises an error from the host filesystem.
Related Io functions
Mat
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
Tabular
csvread · csvwrite · detectImportOptions · dlmread · dlmwrite · readmatrix · spreadsheetImportOptions · writecell · writematrix · xlsread
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 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 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.