|On this page…|
This example shows how to change and save part of a variable in a MAT-file. To run the code in this example, create a Version 7.3 MAT-file with two variables.
A = rand(5); B = ones(4,8); save example.mat A B -v7.3; clear A B
Update the values in the first row of variable B in example.mat.
example = matfile('example.mat','Writable',true) example.B(1,:) = 2 * example.B(1,:);
The matfile function creates a matlab.io.MatFile object that corresponds to a MAT-file:
matlab.io.MatFile Properties: Properties.Source: C:\Documents\MATLAB\example.mat Properties.Writable: true A: [5x5 double] B: [4x8 double]
When you index into objects associated with Version 7.3 MAT-files, MATLAB® loads and saves only the part of the variable that you specify. This partial loading or saving requires less memory than load or save commands, which always operate on entire variables.
For very large files, the best practice is to read and write as much data into memory as possible at a time. Otherwise, repeated file access negatively impacts the performance of your code. For example, suppose your file contains many rows and columns, and loading a single row requires most of the available memory. Rather than updating one element at a time, update each row.
example = matfile('example.mat','Writable',true); [nrowsB,ncolsB] = size(example,'B'); for row = 1:nrowsB example.B(row,:) = row * example.B(row,:); end
If memory is not a concern, you can update the entire contents of a variable at a time, such as
example = matfile('example.mat','Writable',true); example.B = 10 * example.B;
Alternatively, update a variable by calling the save function with the -append option. The -append option requests that the save function replace only the specified variable, B, and leave other variables in the file intact:
load('example.mat','B'); B(1,:) = 2 * B(1,:); save('example.mat','-append','B');
This method always requires that you load and save the entire variable.
Use either method to add a variable to the file. For example, this code
example = matfile('example.mat','Writable',true); example.C = magic(8);
performs the same save operation as
C = magic(8); save('example.mat','-append','C'); clear C
Any load or save operation that uses a matlab.io.MatFile object associated with a Version 7 or earlier MAT-file temporarily loads the entire variable into memory.
The matfile function creates files in Version 7.3 format. For example, this code
newfile = matfile('newfile.mat');
creates a MAT-file that supports partial loading and saving.
However, by default, the save function creates Version 7 MAT-files. Convert existing MAT-files to Version 7.3 by calling the save function with the -v7.3 option, such as
To change your preferences to save new files in Version 7.3 format, access the Environment section on the Home tab, and click Preferences. Select MATLAB > General > MAT-Files.