Is it More Efficient to Load a Subset of Variables from a .mat File Rather than All of the Variables?
Show older comments
Suppose I have a .mat file and an application that only needs to use a subset of the variables in the .mat file.
Option 1:
s = load('matfile.mat'); % load the entire file
% use s.v1, s.v2, s.x1, s.x2 etc. as needed
Option 2:
variables = {"v*","x*"}; % create a list of neeeded variables
s = load('matfile.mat',variables{:});
% use s.v1, s.v2, s.x1, s.x2 etc. as needed
Under what conditions, if any, would Option 2 be much more faster than Option 1? I realize that's a subjective measure, so I guess I'm interested in any noticeable improvement in run time as this workflow has to loop over many mat files (which I guess is still subjective ....)
Assumptions:
- matfile.mat is in -v7 format with compression
- matfile.mat contains 1000 or more variables
- each variable is column vector of doubles with numel = 1000
- The number of variables to load is on the order of 20
- R2024b
- Is there anything else relevant?
Does the answer change with any changes to the stated assumptions? I'm particularly curious about the effect of compression ...
I checked @doc:load for guidance, but didn't find any.
Also, is there any way to (easily) programmatically determine the format and compression of matfile.mat? I'm kind of surprised that such details aren't accessbile through @doc:matfile.
1 Comment
(6) Is there anything else relevant?
The fact that your example is using wildcards is relevant. It will slow things down (in v7) compared to an explicit list of variables. So, the discussion will depend on whether wildcards are indispensible in what you are doing.
Accepted Answer
More Answers (3)
Walter Roberson
on 30 Sep 2026
Edited: Walter Roberson
on 30 Sep 2026
Experimentally, loading the entire file at once is faster.
fname = 'matfile.mat';
temp = [
cellstr(reshape(string(['a':'z','A':'Z'].') + (1:20), 1, []));
arrayfun(@(idx) rand(1000,1), 1:1040, 'uniform', 0) ];
S = struct(temp{:});
save(fname, '-struct', 'S')
clear temp S
tic;
variables = {"v*","x*"}; % create a list of neeeded variables
s = load(fname,variables{:});
toc
whos s
clear s
tic
s = load('matfile.mat'); % load the entire file
toc
whos s
clear s
%redo selective load under the hypothesis that cache effects might be
%involved
tic;
variables = {"v*","x*"}; % create a list of neeeded variables
s = load(fname,variables{:});
toc
clear s
6 Comments
Nope. The comparison is clouded by several circumstantial factors.
(1) tic...toc instead of timeit()
(2) Use of wildcards '*'
(3) variable subset is scattered throughout the file.
As a counter-example,
fname = 'matfile.mat';
temp = [
cellstr(reshape(string(['a':'z','A':'Z'].') + (1:20), 1, []));
arrayfun(@(idx) rand(1000,1), 1:1040, 'uniform', 0) ];
S = struct(temp{:});
save(fname, '-struct', 'S')
clear temp S
variables = ['a':'z','A':'Z'].'+string(1); % create a list of neeeded variables
%variables = {"*1"};
timeit(@() load(fname,variables{:}) ,1 )
timeit(@() load(fname) ,1)
(3) variable subset is scattered throughout the file.
For kicks, I've used this same experimental set-up to reconfirm (as observed here) that in v7.3, subset reading is both faster and independent of how the variables are distributed in the file.
fname = 'matfile.mat';
temp = [
cellstr(reshape(string(['a':'z','A':'Z'].') + (1:20), 1, []));
arrayfun(@(idx) rand(1000,1), 1:1040, 'uniform', 0) ];
S = struct(temp{:});
save(fname, '-struct', 'S', '-v7.3')
variables = ['a':'z', 'A':'N'].'+"1"; % top-clustered variables
timeit(@() load(fname,variables{:}) ,1 )
variables = {'v','x'}.'+string(1:20); %scattered variables
timeit(@() load(fname,variables{:}) ,1 )
timeit(@() load(fname) ,1) %all variables
Walter Roberson
on 1 Oct 2026
The original code had
variables = {"v*","x*"}; % create a list of neeeded variables
s = load('matfile.mat',variables{:});
so that is wild-card variables being mandated as the access pattern.
OK, but the presence of wildcards does conceal potential efficiency. It forces load() to do more work than it otherwise would.
compareTimes() %v7
compareTimes('-v7.3') % v7.3
function compareTimes(varargin)
fname = 'matfile.mat';
temp = [
cellstr(reshape(string(['a':'z','A':'Z'].') + (1:20), 1, []));
arrayfun(@(idx) rand(1000,1), 1:1040, 'uniform', 0) ];
S = struct(temp{:});
save(fname, '-struct', 'S', varargin{:})
variables = string(['a':'z','A':'Z'].') + 1; %explicit (no wildcards)
timeit(@() load(fname,variables{:}) ,1 )
variables = {'*1'}; %wildcards
timeit(@() load(fname,variables{:}) ,1)
timeit(@() load(fname) ,1) %Total test
end
dpb
on 1 Oct 2026
Would
v=whos(-'file',fname,wildcardpattern);
v={v.name}.';
then pass v resolve that, maybe? Or would the added overhead outweigh any benefit?
@Paul, try the following for a drop-in replacement -- it kept nagging at me that this ought to be pretty easy and after some head scratching, decided it was not that hard to create a custom .mat file replacement file that should outperform it from an i/o speed standpoint but still allow keeping all the needed info to reconstruct the data in its entirety.
The "trick" was to write a header into the file containing the variable names and then the data as a flat file; that is then sufficient to restore completely.
To test this, simply call binaryWriter in the workspace with a list of the variables and the data array associated with it as struct2array(S), then you should be able to replace your LOAD calls with a subset of those variables with a call to binaryReader and have back the identical struct as you're presently getting with LOAD and no following code should need modification. (Confession, I hate writing help for functions; these were AI generated with a little editing given a prototype and the purpose. That is, I think, something I'll keep on as a general practice, it didn't do badly at all :>) )
The following minimal working example illustrates the use. The text compare is, as is MATLAB case sensitive but as written doesn't support the wildcard case; you'll need to replace the ismember() logic in the reader with contains() with a pattern match or a regex expression to add that feature.
This also relies on the prior statement that the files are mostly "write once, use lots" so that it would make sense to have the creation code create the binary file besides probably wanting to keep a .mat file for archival purposes. One trade a little extra up front preparation time for the gains during analyses/development/debugging.
Good luck, hope this helps; it was kinda' fun to mess with...it does presume what I think is a fair assessment from @Matt J's timing test that you'll see a significant speedup in the i/o.
s.A=rand(4,1); s.B=randn(4,1);
binaryWriter('S.bin',fieldnames(s),struct2array(s));
S=binaryReader('S.bin','B');
all(S.B==s.B)
function binaryWriter(fileName, varNames, dataMatrix)
%BINARYWRITER Writes a flat binary file with a variable-name header.
% BINARYWRITER(FILENAME, VARNAMES, DATAMATRIX) exports a 2D matrix to a
% flat binary file. The header automatically encodes the number
% of variables and their corresponding names from the cell
% array VARNAMES before streaming the matrix columns sequentially.
%
% See also BINARYREADER, FWRITE, WIDTH.
fid = fopen(fileName, 'w');
if fid < 0, error('binaryWriter:FileError', 'Cannot open file for writing.'); end
c = onCleanup(@() fclose(fid));
numCols = numel(varNames);
assert(numCols==width(dataMatrix),'binaryWriter:DimMismatch', 'Number of names does not match matrix columns.');
fwrite(fid, numCols, 'uint64');
for i = 1:numCols
nameBytes = uint8(varNames{i});
fwrite(fid, numel(nameBytes), 'uint16');
fwrite(fid, nameBytes, 'uint8');
end
fwrite(fid, dataMatrix, 'double');
end
function s=binaryReader(fileName, requestedNames)
%BINARYREADER Fast selective binary loader returning a struct.
% S = BINARYREADER(FILENAME, REQUESTEDNAMES) reads a custom flat binary
% file generated by binaryWriter. It returns the fields specified
% in the cell array REQUESTEDNAMES in struct S.
%
% See also BINARYWRITER, CELL2STRUCT, ISMEMBER.
fid = fopen(fileName, 'r');
if fid < 0, error('binaryReader:FileError', 'Cannot open file for reading.'); end
c = onCleanup(@() fclose(fid));
numCols = fread(fid, 1, 'uint64');
fileVarNames = cell(1, numCols);
for i = 1:numCols
nameLen = fread(fid, 1, 'uint16');
fileVarNames{i} = fread(fid, nameLen, 'uint8=>char').';
end
x = reshape(fread(fid, 'double'), [], numCols);
[tf, loc] = ismember(requestedNames, fileVarNames);
validIndices = loc(tf);
s=cell2struct(num2cell(x(:,validIndices),1), fileVarNames(validIndices),2);
end
2 Comments
Paul
on 6 Oct 2026
dpb
on 7 Oct 2026
Yes, the memory overhead might be an issue, agreed. I chose the fastest system buffering option on the hope you might have lots of RAM and that wouldn't be too much of an issue.
Things are doable with the struct, but get somewhat more complicated although if the prior assumption of constant length is still true, then I guess it's not that bad because can write the data contiguously and compute the offset to each variable for reading from the data starting location -- but, will have to have a marker for where that is since variable names are variable length.
I'd suggest trying one case of the existing and see what time reduction can get to see if it's as promising as Matt's timing indicated it could be.
OK, I'll not wipe out the prior, but it is essentially the same to do the locating explicitly again presuming the constant vector length so that one doesn't have to get that complicated in the header after all.
Adding a set of lengths into the header to derive the offsets or computing and adding the offsets for variable-length fields is doable, but gets a little more complicated.
Again, this is an exact match on retrieval so pattern matching in the reader would be needed to select by wild card matching. This should be nearly as fast on writing but not sure on reading. Since it doesn't read the whole file the absolute number of bytes transferred will be fewer, but it also is mimicking a direct access file so may skip around and buffering may not be as effective. Think it should still show an improvement over the .mat file native format, though.
This you ought to be able to just try direct from command line to test with any existing file that meets the assumption of constant length field variables to compare directly to LOADing same list.
function binaryStrucWriter(fileName, s)
% BINARYSTRUCWRITER Writes a structure directly to a flat binary file.
% BINARYSTRUCWRITER(FILENAME, S) serializes the fields of structure S.
% It inserts the matrix height directly into the top of the file header
% before streaming the field names and raw column vectors sequentially.
fid = fopen(fileName, 'w');
if fid<0, error('binaryStrucWriter:FileError', 'Cannot open file for writing.'); end
c = onCleanup(@() fclose(fid));
fields = fieldnames(s);
numFields = numel(fields);
N = numel(s.(fields{1}));
fwrite(fid, numFields, 'uint64');
fwrite(fid, N, 'uint64');
for i = 1:numFields
field=fields{i}; % Pointer dereference optimization
fwrite(fid, numel(field), 'uint16');
fwrite(fid, field, 'char');
end
for i = 1:numFields
fwrite(fid, s.(fields{i}), 'double');
end
end
function s = binaryStrucReader(fileName, requestedNames)
%BINARYSTRUCREADER Selective binary loader returning a struct.
% S = BINARYSTRUCREADER(FILENAME, REQUESTEDNAMES) parses the dimension
% metadata and name index at the front of the file, then uses fseek to
% extract only the requested columns directly from disk into struct S.
fid = fopen(fileName, 'r');
if fid<0, error('binaryStrucReader:FileError', 'Cannot open file for reading.'); end
c = onCleanup(@() fclose(fid));
numFields = fread(fid, 1, 'uint64');
N = fread(fid, 1, 'uint64');
vnames=cell(1, numFields);
for i=1:numFields
nameLen = fread(fid, 1, 'uint16');
vnames{i} = fread(fid, nameLen, 'uint8=>char').';
end
dataStartOffset = ftell(fid);
bytesPerColumn = 8*N; % N elements * 8 bytes per double
[tf, loc] = ismember(requestedNames, vnames);
validIndices = loc(tf);
numValid = numel(validIndices);
data = cell(1,numValid);
for i = 1:numValid
idx = validIndices(i);
target = dataStartOffset + ((idx - 1) * bytesPerColumn);
fseek(fid, target, 'bof');
data{i} = fread(fid, N, 'double'); % Store directly into cell
end
s=cell2struct(data,vnames(validIndices),2);
end
fname = 'matfile.mat';
bname = 'matfile.bin';
temp = [
cellstr(reshape(string(['a':'z','A':'Z'].') + (1:20), 1, []));
arrayfun(@(idx) rand(1000,1), 1:1040, 'uniform', 0) ];
S = struct(temp{:});
save(fname, '-struct', 'S')
binaryStrucWriter(bname,S) % save the binary file, too
clear temp % keep S to be able to compare to original
variables = ['a':'z','A':'Z'].'+string(1); % create a list of neeeded variables
timeit(@() load(fname,variables{:}) ,1 )/timeit(@() binaryStrucReader(bname,variables))
timeit(@() load(fname),1)/timeit(@() binaryStrucReader(bname,fieldnames(S)))
s=binaryStrucReader(bname,variables); % return the struct to compare
id=randperm(numel(variables),1); % pick a random variable from the list
disp(variables(id))
all(s.(variables{id})==S.(variables{id})) % make sure matches original
OK, it's not 40X as fast, only 5-6X. That's probably close to as good as it's going to get. But still would be something noticeable.
Profiling on desktop system instead of trying it here isolated that 50% of the run time is in the ismember call, the next 35% was the fread(). A loop construct with find(strcmp()) in replacement was another facter of 1.5-2X slower yet. I think this is about the extent of it without a more exotic lookup of where the variables are in the file; back to the other issue of putting them at the beginning of the .mat file.
ADDENDUM
It occurred to me overnight that presuming the use scenario is generally "write once, read often" that the lookup bottleneck could be ameliorated by the expedient of sorting the variable names alphabetically in the header on writing so the reader could use an efficient binary search instead of general lookup. It would not totally eliminate the location time/overhead, but should cut it down significantly.
Also, writing the file in sorted field sequence will ensure the reader only traverses the file sequentially that will minimize wasted i/o buffering misses that the present name sequence might cause. One could help the present version in that regards if ensured that the list of requested variables is in the same order as are the fields in the struct as written.
ADDENDUM SECUNDUM
Well, testing the above hypothesis indicates ismember internal code is still about 10% faster than a base MATLAB binary search so it appears this is the expected performance enhancement without writing a customized mex function for purpose. But, should still be a noticeable improvement to the workflow you outlined previously.
Categories
Find more on Convert Image Type in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!