Workspace Variables and MAT-Files
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. The reference material consulted while preparing these pages is listed in the section bibliography. |
Written against MATLAB R2026b. The sessions below were run in GNU Octave 11.3.0 (MATLAB code that Octave also accepts) and show Octave’s output; MATLAB’s whos and structure displays use a different layout. Features that Octave does not have (matfile, MATLAB’s -v7.3 HDF5 files) are checked against the R2026b documentation and labelled "not run here".
The workspace is the set of variables you have created or loaded in a session. It lives in memory: when you quit MATLAB on the desktop, it is cleared (in MATLAB Online, variables persist between sessions). This page shows how to inspect the workspace, how to remove things from it, and how to save it to disk in a MAT-file and read it back. Statements that create the variables are on Syntax, Statements and Variables; the separate workspaces that functions have are on Workspaces, Scope, Global and Persistent.
Looking at the workspace
The Workspace panel of the desktop lists each variable with its name, value, size and class, and opens the Variables editor on double-click (see Desktop and Command Window). From code you use three functions.
-
wholists the names of the variables in the current workspace. -
whoslists names with size, bytes, class and attributes (such asglobal,sparse,complex,persistent). -
exist("name")returns a number saying whatnameis:1for a variable in the workspace,2for a file (with extension.m,.mlxor.mlapp, or a file with an unregistered extension such as.mator.txt),3for a MEX file,5for a built-in function,6for a P-code file,7for a folder,8for a class,4for a Simulink model, and0when it does not exist or cannot be found. Folders and built-in functions take precedence over files, and variables over everything.
clear
nx = 4; ny = 3; alpha = 1.1e-4;
name = 'plate';
T = zeros(ny, nx);
who
whos
exist('alpha')
exist('sin')
exist('nosuchthing')
Octave 11.3.0 output:
Variables visible from the current scope:
T alpha name nx ny
Variables visible from the current scope:
variables in scope: top scope
Attr Name Size Bytes Class
==== ==== ==== ===== =====
T 3x4 96 double
alpha 1x1 8 double
name 1x5 5 char
nx 1x1 8 double
ny 1x1 8 double
Total is 20 elements using 125 bytes
ans = 1
ans = 5
ans = 0
MATLAB’s whos prints the same information in the columns Name, Size, Bytes, Class and Attributes; for example, the reference page for clear shows a variable b as 1x1, 8 bytes, double. The three exist results (variable, built-in function, nothing) are the documented codes.
who and whos take patterns (who T*) and, with -file, describe a MAT-file without loading it (see Inspecting a MAT-file without loading it).
Removing variables
clear with no arguments removes all variables from the current workspace. With names it removes only those: clear T alpha. Other forms the reference page documents:
-
clear -regexp expr1 ... exprNremoves the variables whose names match any of the regular expressions, for exampleclear -regexp ^Mon ^Tue. -
clear(vars{:})with a cell array of names, the function form to use when the names are in variables. -
clear ItemTypeclears a class of items:variables,functions(compiled scripts, functions and MEX functions, and persistent variables),global,classes,import,java,mex, orall. -
clear global nameremoves a global variable from every workspace; plainclear nameremoves it only from the current one.
clearvars is the more precise relative: it removes variables except those you list (clearvars -except T) and accepts patterns and the -global and -regexp options.
clearvars -except T
Octave 11.3.0 accepted this line and removed every variable except T; the reference page for clearvars in MATLAB documents the same -except option.
Source: MATLAB documentation: clearvars
Why not clear all
clear all removes variables and the compiled functions, classes and MEX functions held in memory, and it also clears persistent and global variables. MATLAB then has to read and compile every file again the next time you call it, which makes the next calls slow, and it can hide mistakes by wiping state a script silently depended on. It also does not do what people want most of the time, which is a clean variable workspace. Use clear (variables) or clearvars instead, clear functions only when you changed a function that is locked in memory, and restart MATLAB if you need a pristine session. A script that starts with clear all also destroys the caller’s variables when it is run from another script.
Saving and loading: save and load
save writes workspace variables to a MAT-file, a binary file with the extension .mat, and load reads them back. The forms of save documented for R2026b are:
save(filename) % all variables
save(filename, variables) % some variables, or fields of a struct
save(filename, variables, fmt) % a file format
save(filename, variables, version) % a MAT-file version
save(filename, variables, version, "-nocompression")
save(filename, variables, "-append")
save filename % command form
Source: MATLAB documentation: save
The options that matter:
| Option | Effect |
|---|---|
|
MAT-file version 7. This is the default for |
|
Version 7.3, based on HDF5: variables larger than 2 GB, partial loading and saving with |
|
Older versions, for sharing with very old releases. Version 4 holds only two-dimensional double, character and sparse arrays. |
|
Skip compression, for faster saves. Only with |
|
Add variables to an existing file, replacing a variable with the same name. To append to a Version 6 file you must also give |
|
Write plain text of numeric data (8 digits), with no variable names. A |
|
Save the fields of a scalar structure as separate variables. |
Save and load a heatflow state
This session writes a state to a MAT-file in the temporary folder, loads it back into a structure, then shows -struct. It is the Octave 11.3.0 run:
f = fullfile(tempdir, 'plate_state.mat');
save(f, 'T', 'alpha');
clear T alpha
S = load(f)
exist('T')
load(f);
exist('T')
s = struct('nx', nx, 'ny', ny);
save(f, '-struct', 's');
R = load(f)
Octave 11.3.0 output:
S =
scalar structure containing the fields:
T =
0 0 0 0
0 0 0 0
0 0 0 0
alpha = 1.1000e-04
ans = 0
ans = 1
R =
scalar structure containing the fields:
nx = 4
ny = 3
Step by step:
-
save(f, 'T', 'alpha')writes the two variables. -
After
clear T alpha,S = load(f)reads the file into a structureSwith fieldsTandalpha. The workspace is untouched:exist('T')is still0. -
load(f)with no output argument puts the variables straight into the workspace, soexist('T')becomes1. -
save(f, '-struct', 's')stores each field of the structuresas its own variable, so the file containsnxandny, and the nextloadreturns them.
The MATLAB documentation explains why the second form exists. Loading without an output argument overwrites any variable that has the same name in your workspace, without asking and without a warning ("poofing" variables into existence). A script that loads a file and then uses a variable it did not create is also hard to read. Prefer the structure form, S = load("durer"), and then use S.X, and select the variables you want with load(filename, "X", "map").
Command form and function form
save test.mat and save("test.mat") are equivalent, and so are load durer and load("durer"). The command form (see Desktop and Command Window and Syntax, Statements and Variables) cannot be used when an input is a variable: with filename = "test.mat", save filename would write a file called filename.mat. Use the function form save(filename).
Inspecting a MAT-file without loading it
whos -file filename lists the name, size, bytes and class of every variable in a MAT-file without reading the data into memory, and the Files panel’s Preview button shows the same with values. The documentation’s -struct example saves s1.a = 12.7, s1.b = {"abc",[4 5; 6 7]} and s1.c = "Hello!", and whos("-file","newstruct.mat") then lists a (1x1 double), b (1x2 cell) and c (1x1 string).
whos -file plate_state.mat
Octave 11.3.0 accepts the same call, whos("-file", f), and printed the table of the two variables saved above (T, 3x4, 96 bytes, double; alpha, 1x1, 8 bytes, double) under the heading "Variables in the file". MATLAB prints the columns Name, Size, Bytes, Class and Attributes.
MAT-file versions
The documentation lists these versions (all MATLAB releases since R2006b read all of them):
| Version | Release introduced | Adds | Limits |
|---|---|---|---|
7.3 |
R2006b |
HDF5-based format, partial loading and saving ( |
variables of 2 GB and more on 64-bit computers |
7 |
R14 |
Unicode characters, compression (default) |
2 GB per variable |
6 |
MATLAB 5 (R8) |
N-dimensional arrays, cell arrays, structures, long variable names |
no compression, 2 GB per variable |
4 |
all releases |
two-dimensional double, character and sparse arrays |
no compression, 100,000,000 elements per array |
By default save creates Version 7 files; the exception is matfile, which creates Version 7.3 files for new files. Change the default in Settings under MATLAB > General > MAT and FIG Files. Save to a version other than the default when you want to share with earlier releases, use version 7.3 features, save faster with no compression, or make a smaller file with compression. Version 7.3 files need some storage overhead to describe their contents, so files of cell arrays and structures are sometimes larger than their Version 7 equivalents. The HDF5 format of Version 7.3 is documented by the HDF Group, which means that other languages can read the data (Calling Python from MATLAB shows a Python route).
Partial reading and writing: matfile
matObj = matfile(filename) creates a matlab.io.MatFile object connected to a MAT-file. You read and write variables, or parts of them, without loading the file into memory. This is useful when a variable is too large to fit in memory, and it needs Version 7.3 files for partial access. matfile(filename, "Writable", true) enables writing; the default is writable for a new file and read-only for an existing one. If filename has no extension, MATLAB looks for filename.mat, and if the file does not exist it creates a Version 7.3 file at the first assignment. Remote locations such as Amazon S3 (s3://...) are accepted in the file name.
m = matfile("history.mat", "Writable", true);
m.T = zeros(64, 64, 100);
m.T(:, :, 1) = ones(64);
slice = m.T(:, :, 1);
Not run here: matfile is not available in Octave 11.3.0. The four lines create a 100-step history on disk, overwrite its first time step with ones and read that step back, never holding the whole array in memory. Saving the part of a variable with matfile is also what the save documentation recommends for very large data. For data sets that exceed memory in other ways, see Large Data, Datastores and Tall Arrays.
Source: MATLAB documentation: matfile
Pitfalls
-
loadoverwrites silently. UseS = load(...)(see above). -
Forgetting that
-asciiloses the names and the types. Use a MAT-file orwritematrix(Reading and Writing Tabular Data). -
clear allin scripts and in the first line of every program (see above). -
A MAT-file saved with a newer feature can be unreadable on older releases; save with
-v7or lower for sharing. -
Variables larger than 2 GB fail with
-v7; use-v7.3. -
Never load MAT-files from untrusted sources without checking: they can contain class objects, and loading an object can run that class’s
loadobjmethod.
Where older books differ
Books for MATLAB 7 describe the workspace browser and the Import Wizard (today’s Workspace panel and Import Tool), and clear all as the standard first line of a script. Both the tools and the advice have changed. Version 7.3 files, the matfile object and -struct appear in recent documentation but are often missing from older books.