MAT-Files: save & load
Text formats such as CSV are great for exchanging tables, but they lose information: a struct, a cell array, an int8 vector or a logical mask turns into plain text that you have to rebuild by hand. MAT-files are MATLAB's own binary format. save writes workspace variables to one with their names, types and exact values, and load restores them, unchanged and very fast. They're the natural way to save intermediate results, cache an expensive calculation or hand data to a colleague who also uses MATLAB, Octave, Python (scipy.io.loadmat) or R.
| Call | Effect |
|---|---|
save(file) |
All workspace variables |
save(file, 'x', 'y') |
Only the named variables |
save(file, '-struct', 's') |
Each field of struct s as a separate variable |
save(file, 'z', '-append') |
Add or replace z in an existing file |
save(file, 'M', '-ascii') |
Numeric matrix as plain text (no names or types) |
S = load(file) |
All variables, as fields of struct S |
S = load(file, 'x') |
Only x |
load(file) |
Variables straight into the workspace |
who('-file', file), whos('-file', file) |
List what's inside without loading |
A portability trap: Octave's default format
In MATLAB, save('results.mat', 'x') writes a binary MAT-file. Octave's default is its own text format, even when the file name ends in .mat. MATLAB can't read that file. Adding the format option -v7 gives a real MAT-file in both programs (in MATLAB, -v7 is just the long-standing format, so nothing changes there). All examples below use it:
x = [1 2 3];
save('octave_default.mat', 'x'); % Octave: text format!
save('portable.mat', 'x', '-v7'); % MAT-file version 7 in both programs
for f = {'octave_default.mat', 'portable.mat'}
fid = fopen(f{1}, 'r');
head = fread(fid, 10, '*char')'; % the first 10 bytes of the file
fclose(fid);
fprintf('%-20s starts with "%s"\n', f{1}, head);
endoctave_default.mat starts with "# Created "
portable.mat starts with "MATLAB 5.0"
A real MAT-file starts with the text MATLAB 5.0 MAT-file, which is what MATLAB looks for. (In MATLAB, the first file would start with those words as well.) In your own Octave setup you can make -v7 the default with save_default_options('-v7') in your startup file.
Saving and loading variables
Save the variables you need by name, then load them back. The recommended form of load returns a struct: you see exactly which variables arrive, and none of your existing variables are silently overwritten:
temps = [21.5 22.0 23.4];
station = 'Bergen';
flags = logical([1 0 1]);
counts = int16([12 7 30]);
save('station.mat', 'temps', 'station', 'flags', 'counts', '-v7');
clear temps station flags counts % pretend we start a new session
S = load('station.mat');
disp(fieldnames(S)')
fprintf('%s: mean %.2f, classes %s / %s\n', S.station, mean(S.temps), class(S.flags), class(S.counts));
T = load('station.mat', 'temps'); % just one variable
fprintf('fields loaded: %d\n', numel(fieldnames(T)));{
[1,1] = temps
[1,2] = station
[1,3] = flags
[1,4] = counts
}
Bergen: mean 22.30, classes logical / int16
fields loaded: 1
The command syntax save station.mat temps station -v7 and load station.mat does the same thing with less typing, and is common at the command line. But file and variable names are then fixed text; when the name is in a variable, use the function form: save(fname, 'temps', '-v7').
load(file) without an output creates the variables directly in the workspace. It's convenient interactively, but in scripts and functions it makes variables appear "out of nowhere", which is hard to read and can't be checked by the editor. Prefer S = load(file).
Everything round-trips
Unlike text formats, a MAT-file keeps every type: integers stay integers, cells stay cells, structs keep their fields, complex numbers keep their imaginary part:
data.id = int8([1 -2 3]);
data.ok = true(2);
data.notes = {'first', 'second', [10 20]};
data.people = struct('name', {'Ada', 'Bo'}, 'age', {36, 41});
data.z = 3 - 4i;
save('mixed.mat', '-struct', 'data', '-v7'); % each field becomes a variable
S = load('mixed.mat');
names = fieldnames(S);
for k = 1:numel(names)
v = S.(names{k});
fprintf('%-7s %-8s %-4s unchanged: %d\n', names{k}, class(v), mat2str(size(v)), isequal(v, data.(names{k})));
endid int8 [1 3] unchanged: 1
notes cell [1 3] unchanged: 1
ok logical [2 2] unchanged: 1
people struct [1 2] unchanged: 1
z double [1 1] unchanged: 1
-struct saves the fields of a struct as separate variables, and S = load(...) gathers them into a struct again. Together they let a function save and return "a bundle of results" without any variable names leaking into the caller's workspace.
Inspecting and appending
who('-file', name) lists the variable names in a file without loading the data, which is useful for big files. whos('-file', name) adds sizes and classes (its table layout differs between MATLAB and Octave, so the example prints the names only). -append adds a variable to an existing file, or replaces it if one with the same name is already there:
a = magic(3); b = 'hello';
save('notes.mat', 'a', 'b', '-v7');
c = {1, 2};
save('notes.mat', 'c', '-append', '-v7'); % add c
a = 0;
save('notes.mat', 'a', '-append', '-v7'); % replace a
fprintf('variables: %s\n', strjoin(who('-file', 'notes.mat'), ', '));
S = load('notes.mat', 'a');
fprintf('a is now %g\n', S.a);
fprintf('file exists: %d\n', isfile('notes.mat'));variables: a, b, c
a is now 0
file exists: 1
Text instead of binary: -ascii
save(file, 'M', '-ascii') writes a numeric matrix as plain text, one row per line, and load(file) (or load(file, '-ascii')) reads it back as a matrix. There are no variable names or types in such a file: load returns just the numbers. Add '-double' for 16 significant digits instead of 8, and '-tabs' for tab separators:
M = [1.5 2 3; 4 5 6.25];
save('matrix.txt', 'M', '-ascii');
N = load('matrix.txt');
fprintf('size %s, equal: %d\n', mat2str(size(N)), isequal(M, N));
P = [pi exp(1)];
save('pi8.txt', 'P', '-ascii'); % 8 significant digits
save('pi16.txt', 'P', '-ascii', '-double'); % 16 significant digits
fprintf('error with 8 digits: %.1e, with 16: %.1e\n', ...
max(abs(load('pi8.txt') - P)), max(abs(load('pi16.txt') - P)));size [2 3], equal: 1
error with 8 digits: 3.6e-09, with 16: 0.0e+00
The exact text layout written by -ascii (spacing and exponent style) differs between MATLAB and Octave, but both read each other's files. For files that people should also read, a formatted CSV or fprintf is usually nicer.
MAT-file versions and matfile
| Option | Format | Notes |
|---|---|---|
-v7 |
Compressed binary | MATLAB's default; read and written by MATLAB, Octave, SciPy |
-v6 |
Uncompressed binary | Faster for data that doesn't compress |
-v7.3 |
HDF5-based | Needed for variables over 2 GB; allows partial loading. Octave 11 can't write it ("not yet implemented") |
-ascii |
Text | Numeric matrices only |
For very large -v7.3 files, MATLAB's matfile reads and writes parts of a variable without loading all of it:
% MATLAB only
m = matfile('big.mat', 'Writable', true);
m.A = zeros(1000, 1000); % creates A in the file
m.A(1:2, 1:3) = [1 2 3; 4 5 6]; % change a corner without loading A
block = m.A(1:2, 1:3)MATLAB output:
block =
1 2 3
4 5 6Octave 11 has no matfile. There, split big data into several smaller variables or files and load only the ones you need: S = load(file, 'part3').
Summary
save(file, vars..., '-v7')writes a MAT-file that MATLAB, Octave and Python can read; without-v7, Octave writes its own text format.S = load(file)returns a struct and is clearer than loading into the workspace.- MAT-files keep every type exactly;
-structsaves struct fields as variables;-appendadds or replaces variables. -asciiwrites plain numeric text (8 digits, or 16 with-double).-v7.3andmatfile(MATLAB) handle data too big for memory.
Next: Importing & Exporting Data.
Test yourself
Why add '-v7' to save in code that should work in MATLAB and Octave?
- It makes the file smaller in MATLAB
- Octave's default save format is text, which MATLAB can't load
- -v7 is required for structs
- It encrypts the file
What does S = load('results.mat') return?
- Nothing; the variables appear in the workspace
- A struct whose fields are the saved variables
- A cell array of variable names
- The file size
Which option adds a variable to an existing MAT-file without removing the others?
'-add''-append''-update''-struct'