%% Read One Array at a Time From Large MAT-File
% You can create a datastore to read from a large MAT-file that does not necessarily fit in memory. Assuming that each array in the large MAT-file fits in the available memory, create a datastore to read and process the data in three steps:
% Write a custom reading function that reads one array at a time from a MAT-file.
% Set up the parameters of the datastore function to perform partial reads.
% Read one array at a time from the MAT-file.
% Write a custom function that reads one array at time from MAT-file. The function must have a signature as described in the @ReadFcn argument of FileDatastore. Save this file in your working folder or in a folder that is on the MATLAB path. For this example, a custom function load_variable is included here.

type load_variable.m

% Create and setup a FileDatastore containing  accidents.mat. Specify the datastore parameters to use 'partialfile' as the read mode and load_variable as the custom reading function.

fds = fileDatastore('accidents.mat','ReadMode','partialfile','ReadFcn',@load_variable);

% Read the first three variables from the file using the datastore. The file accidents.mat contains nine variables and every call to read returns one variable. Therefore, to get the first three variables, call the read function three times.

data = read(fds)
data = read(fds)
data = read(fds)

% Note that the sample file accidents.mat  is small and fits in memory, but you can expect similar results for large MAT-files that do not fit in memory.
% Copyright 2018 The MathWorks, Inc.