%% Save and Load Using the matfile Function
% This example shows how to load, modify, and save part of a variable in an existing MAT-file using the matfile function.
% Create a Version 7.3 MAT-file with two variables, A and B.

A = rand(5);
B = magic(10);
save example.mat A B -v7.3;
clear A B

%
% Construct a MatFile object from the MAT-file, example.mat. The matfile function creates a MatFile object that corresponds to the MAT-file and contains the properties of the MatFile object. By default, matfile only permits loading from existing MAT-files.

exampleObject = matfile('example.mat');

%
% To enable saving, call matfile with the Writable parameter.

exampleObject = matfile('example.mat','Writable',true);

%
% Alternatively, construct the object and set Properties.Writable in separate steps.

exampleObject = matfile('example.mat');
exampleObject.Properties.Writable = true;

%
% Load the first row of B from example.mat into variable firstRowB and modify the data. When you index into objects associated with Version 7.3 MAT-files, MATLAB® loads only the part of the variable that you specify.

firstRowB = exampleObject.B(1,:); 
firstRowB = 2 * firstRowB;

%
% Update the values in the first row of variable B in example.mat using the values stored in firstRowB.

exampleObject.B(1,:) = firstRowB;

%
% 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 that your file contains many rows and columns, and that loading a single row requires most of the available memory. Rather than updating one element at a time, update each row.

[nrowsB,ncolsB] = size(exampleObject,'B');
for row = 1:nrowsB
  exampleObject.B(row,:) = row * exampleObject.B(row,:);
end

%
% If memory is not a concern, you can update the entire contents of a variable at a time.

exampleObject.B = 10 * exampleObject.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. This method always requires that you load and save the entire variable.

load('example.mat','B');
B(1,:) = 2 * B(1,:);
save('example.mat','-append','B');

%
% Add a variable to the file using the matlab.io.MatFile object.

exampleObject.C = magic(8);

%
% You also can add the variable by calling the save function with the  -append option.

C = magic(8);
save('example.mat','-append','C');
clear C

% Copyright 2012 The MathWorks, Inc.