Is it More Efficient to Load a Subset of Variables from a .mat File Rather than All of the Variables?

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:
  1. matfile.mat is in -v7 format with compression
  2. matfile.mat contains 1000 or more variables
  3. each variable is column vector of doubles with numel = 1000
  4. The number of variables to load is on the order of 20
  5. R2024b
  6. 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.

Sign in to comment.

 Accepted Answer

I would expect Option 2 to be more efficient, especially when compression is applied. By specifying a subset of variables, load() has fewer variables it needs to uncompress. You should, of course, test this on your specific files.
As for identifying format, perhaps as follows?
a = rand(1000);
b = rand(1000);
save v6file a b -v6
save v7file a b -v7
save v7nc a b -v7 -nocompression
save v73file a b -v7.3
save v73nc a b -v7.3 -nocompression
matfileInfo("v6file.mat")
ans = struct with fields:
Format: "Level-5" Compression: "uncompressed"
matfileInfo("v7file.mat")
ans = struct with fields:
Format: "Level-5" Compression: "compressed"
matfileInfo("v7nc.mat")
ans = struct with fields:
Format: "Level-5" Compression: "uncompressed"
matfileInfo("v73file.mat")
ans = struct with fields:
Format: "v7.3" Compression: "compressed" CompressionLevel: 3
matfileInfo("v73nc.mat")
ans = struct with fields:
Format: "v7.3" Compression: "uncompressed" CompressionLevel: 0
function info = matfileInfo(filename)
%MATFILEINFO Determine MAT-file format and compression.
%
% INFO = MATFILEINFO(FILENAME) returns:
%
% Format - "v7.3", "Level-5", or "unknown"
% Compression - "compressed", "uncompressed", or "mixed"
%
% For Level-5 MAT-files (-v6/-v7), compression is determined from
% top-level miCOMPRESSED data-element tags.
%
% For v7.3 MAT-files, compression is determined from HDF5 filters.
arguments
filename (1,1) string
end
fid = fopen(filename,'r','ieee-le');
if fid < 0
error("Could not open file '%s'.",filename)
end
c = onCleanup(@() fclose(fid));
%% Read MAT-file header
header = char(fread(fid,116,'uint8=>char').');
%% v7.3
if startsWith(header,'MATLAB 7.3 MAT-file')
info.Format = "v7.3";
H = h5info(filename);
levels = nan(1,numel(H.Datasets));
for k = 1:numel(H.Datasets)
levels(k) = getCompressionLevel(H.Datasets(k).Filters);
end
info.Compression = summarize(levels > 0);
% Report compression level if it is uniform across datasets.
u = unique(levels(~isnan(levels)));
if isempty(u)
info.CompressionLevel = NaN;
elseif isscalar(u)
info.CompressionLevel = u;
else
info.CompressionLevel = NaN; % different levels among datasets
end
return
end
%% Level-5
if ~startsWith(header,'MATLAB 5.0 MAT-file')
info.Format = "unknown";
info.Compression = "unknown";
return
end
info.Format = "Level-5";
% Bytes 127-128 contain endian indicator.
fseek(fid,126,'bof');
endian = char(fread(fid,2,'uint8=>char').');
switch endian
case 'IM'
swap = false; % little endian
case 'MI'
swap = true; % big endian
otherwise
error("Invalid Level-5 MAT-file endian indicator.")
end
%% Scan top-level data elements
fseek(fid,128,'bof');
compressed = [];
while true
dataType = fread(fid,1,'uint32');
if isempty(dataType)
break
end
nBytes = fread(fid,1,'uint32');
if isempty(nBytes)
error("Unexpected end of MAT-file.")
end
if swap
dataType = swapbytes(dataType);
nBytes = swapbytes(nBytes);
end
% Level-5 types:
%
% miMATRIX = 14
% miCOMPRESSED = 15
compressed(end+1) = (dataType == 15); %#ok<AGROW>
if dataType == 15 % miCOMPRESSED
nSkip = double(nBytes); % no padding
else
nSkip = 8*ceil(double(nBytes)/8);
end
status = fseek(fid,nSkip,'cof');
if status ~= 0
error("Invalid MAT-file data element.")
end
end
info.Compression = summarize(compressed);
end
function level = getCompressionLevel(filters)
level = NaN;
for k = 1:numel(filters)
if strcmpi(filters(k).Name,'deflate')
level = double(filters(k).Data);
return
end
end
end
function s = summarize(tf)
if isempty(tf)
s = "uncompressed";
elseif all(tf)
s = "compressed";
elseif any(tf)
s = "mixed";
else
s = "uncompressed";
end
end

31 Comments

"... when compression is applied." That assumes that compression is applied to each variable independently. Do we know for sure that's how compression works? I can't find anything on point.
I've found:
"Reduce the time required to load and save some files by storing uncompressed data."
"Data compression and decompression slow down all save operations and some load operations."
"In some cases, loading compressed data actually can be faster than loading uncompressed data."
The first and second statements, from the same doc page, seem to be in tension with each other.
On the one hand, compression-by-variable would (probably?) make loading a subset of variables faster as you described, though there must be some sort of trade-off between the size of the variable and how much compression is actually achieved. Unlcear to me what the impact would be if loading the entire file. OTOH, compression-by-file, so to speak and assuming that's even feasible, has potential for much smaller file size, possibly at the expense of speed of loading just a few variables, but not much of a hit if loading the entire file.
Yes, I'll need to do some testing.
Thanks for posting the code (which is only "easily" for me because you did the hard work!). Maybe a reasonable enhancement request for Mathworks to provide such functionality?
Another possible issue to consider is if matfile.mat is stored locally or on a network drive.
That assumes that compression is applied to each variable independently. Do we know for sure that's how compression works? I can't find anything on point.
It is strongly suggested by this document,
In particular, on p. 1-8:
"Because it compresses each variable individually, MATLAB can read a compressed MAT-file like any other MAT-file..."
and also further down the page,
"MATLAB stores compressed data in zlib-compressed MATLAB arrays. Each compressed variable is stored complete with its tags and data field in the same format as uncompressed variables, as described in “Data Element Format” on page 1-5. The difference is that the entire variable is compressed into a data buffer, and this buffer is preceded by an 8-byte tag named miCOMPRESSED. The tag contains the length of the compressed buffer."
"That assumes that compression is applied to each variable independently. Do we know for sure that's how compression works?"
AFAICT thsi is not documented. But I think we can deduce that is how it works by the fact that mat files seem to provide random access, which implies that each variable can be accessed & compressed independently.
That assumes that compression is applied to each variable independently. Do we know for sure that's how compression works? I can't find anything on point.
Further evidence of this is that you can construct .mat files with mixtures of compressed and non-compressed variables, which incidentally the suggested matfileInfo() function can detect:
A = rand(1000);
B = rand(1000);
C = rand(1000);
save("mixed7.mat","A","B","-v7")
save("mixed7.mat","C","-append","-nocompression")
matfileInfo("mixed7.mat")
ans = struct with fields:
Format: "Level-5" Compression: "mixed"
Great find. Sounds unequivocal to me.
I thought the pdf doc was supposed to be essentially the same as the regular doc, just in a more formal format. But for the life of me I can't find the mat file information from the pdf document you posted in the regular doc, so I guess I was wrong (I thought this exact issue was discussed in another Answer thread; I'll see if I can find it). More problematic is that I can't find a link to the pdf_doc from Help Center, so it would be hard to find that information even if one knew that it might conain additional information not included in the regular doc. (see below)
The existence of the pdf version of the documentation book was identified by @Steven Lord in this comment. @dpb inquired about the equivalence between the pdf and the online documentation in the subsequent comment in that thread, but the inquiry was left unanswered.
Apparently one has to select a product first, and then the pdf doucmenation is easily found: Where do I find the PDF documentation for MATLAB and other MathWorks products? - MATLAB Answers - MATLAB Central, just can't get to it from the Help home page.
I would expect Option 2 to be more efficient, especially when compression is applied.
Here's a simple test. Somewhat consistent with what I predicted, the time difference is larger with compression for v7, although not for v7.3:
for i=1:6000
S.("A"+i)=rand(1000,1);
end
save dotmat -struct S -v7.3 %compressed
TimeTest()
ans = 0.1192
ans = 0.2578
save dotmat -struct S -v7.3 -nocompression
TimeTest()
ans = 0.1140
ans = 0.2469
save dotmat -struct S %compressed
TimeTest()
ans = 0.0708
ans = 0.3393
save dotmat -struct S -nocompression
TimeTest()
ans = 0.0160
ans = 0.0412
function TimeTest
timeit(@() load('dotmat','A3000') ,1)
timeit(@() load('dotmat') ,1)
end
From a practical standpoint besides simply the LOAD time, I'd think bringing some thousand unused variables into the workspace would contribute mightily to potential memory fragmentation besides whatever behind-the-scenes memory footprint there is in creating the variable reference itself besides the actual data storage.
If this is some real scenario, might want to consider matfile although there are caveats with compression regarding to indexing addressing to watch out for.
Another thought would be to avoid the namespace pollution and consequent variable name resolution lookup, the multitude could be kept in a single cell array. Doesn't help with actual memory fragmentation, but would eliminate having the 1000+ names in the name space management.
My assumption 2 was way off, each file has a lot more than 1000 variables.
I did some timeit testing on one file and found loading the subset was about 0.6x the time of loading the full file. My timeit testing was structured like
timeit(@() fun1(matfile))
timeit(@() fun2(matfile))
function s = fun1(matfile)
s = load(matfile)
end
function s = fun2(matfile)
vars = {whatever}
s = load(matfile,vars{:});
end
Consequently, I changed the real application, which uses rowfun to loop over many such files (the only difference among the files is the numel of the stored variables), to only read in the subset, and it felt like it actually ran slower. I checked with the profiler and the load command was much slower when loading the subset as opposed to loading the full file. Ran the profiling a few times to make sure I wasn't hallucinating. No idea what could be the difference between the timeit testing and the actual code, but for now I'm still loading the full file.
I tried matfile once before (maybe around R2020 or so) and found that it slowed things down too much, and the files I were working with were manageable w/o using matfile. So I got away from matfile pretty quickly.
Here's an elaboration of my earlier test, but reading in larger subsets of variables. The results seem to say that for v7.3, reading in subsets is uniformly more efficient than reading in the whole file.
Conversely, with v7, the efficiency depends on how the subset is distributed across the matfile. A subset concentrated near the bottom of the file or scattered throughout will indeed read in slower than a read of the whole file. However, if the subset is concentrated toward the top of the file, it reads in substantially faster. Basically, the efficiency depends on how much of the file the reader needs to traverse...
for i=1:6000
S.("A"+i)=rand(1000,1);
end
save dotmat -struct S -v7.3 %compressed
TimeTest()
ans = 0.1242
ans = 0.1158
ans = 0.1186
ans = 0.2710
save dotmat -struct S -v7.3 -nocompression
TimeTest()
ans = 0.1178
ans = 0.1158
ans = 0.1128
ans = 0.2498
save dotmat -struct S %compressed
TimeTest()
ans = 0.0531
ans = 0.9332
ans = 0.4548
ans = 0.3432
save dotmat -struct S -nocompression
TimeTest()
ans = 0.0128
ans = 0.1554
ans = 0.0843
ans = 0.0389
function TimeTest
subset="A"+(1:20); %concentrated at the top
timeit(@() load('dotmat',subset{:}) ,1)
subset="A"+(5981:6000); %concentrated at the bottom
timeit(@() load('dotmat',subset{:}) ,1)
subset="A"+(1:300:6000); %scattered
timeit(@() load('dotmat',subset{:}) ,1)
timeit(@() load('dotmat') ,1) %read whole file
end
I was wondering about whether or not the distribution of the subset in the file makes a difference.
My vars in the load command does use wildcards, but I did that the same way in the timeit test and the actual code.
I still don't understand why I saw a discrepancy between the simple timeit test and the actual code.
Maybe I'll try to not use wildcards in the vars list and see what happens ...
I think I was hallucinating with my timeit tests. I went back to it today and clearly saw that the full load was faster than the subset load, consistent with the profiling of the actual application.
I also tried getting rid of the wildcards in vars. Basically, I did something like
w = whos('-file',matfile); % get all of the variables
w = w(startsWith(w,["x","y"]));
s = load(matfile,w{:});
This approach was considerably slower than the other two based on timeit.
Still sticking with the full load for now; might play around with v7.3 format and/or restructuring the file so that the vars that I know that I want are at or near the top when the mat file is generated to begin with.
This approach was considerably slower than the other two based on timeit.
But are you timing the load operation in isolation? The whos() operation will add overhead of its own, so if that is included in the execution time measurement, it makes sense that it would be slower.
If you are sticking to v7, the optimization you would need to do is,
(1) pre-compute your variables list so that it isn't part of the loop.
(2) move all those variables to the top of the file.
The timing test included the overhead of the whos operation as that whould be how I would do it in the actual code, at least as things stand now. I might go back and try it as if I know a priori the names of all of the variables as that might be an option.
Is there any practical way to rearrange the order in a .mat file, though?
Although if there were some way to know a priori the needed variables, I don't suppose that would be (yet) in the originating code but only in the piece(s) wanting/needing them? That could lead to a more efficient SAVEing if were somehow to be so.
I also wonder if it would be more effective to have more, but shorter .mat files so retrieval wouldn't be as long although multiple LOADs might still be more costly.
But, overall, unless this is an operation that has to be done deep in a loop, it doesn't seem as though it would be a major hurdle? Trying to figure out the use here...
Is there any practical way to rearrange the order in a .mat file, though?
By recreating it...?
Only way I knew, just asking...
However, LOADing all to have them to write, building an ordererd list with which to SAVE in order to then LOAD a subset slightly quicker than from an uordered .mat file doesn't seem terribly likely to be faster overall. ;>)
The only real savings I can see from what has been provided so far is to be able to know a priori which are the ones going to be needed and to then SAVE only those to an active .mat file relegating the rest of the cast of thousands to a background .mat file. But, the use case is still a puzzle as to how this would arise wherein a few hundredths of a second difference would matter significantly?
But, the use case is still a puzzle as to how this would arise wherein a few hundredths of a second difference would matter significantly?
I don't know why you would think "a few hundredths". If you believe my tests above, the diffrence can be around 0.5 seconds.
OK, so say it's a second even; how long is the job that uses it?
And the prior about how one is going to get it sorted is still going to be an issue unless it can be determined a priori which need to be first.
I still don't follow the use case that would really justify worrying too much about it other than simply hypothetical and investigating MATLAB behavior. There may well be some well defined pattern in which it would be possible to make it matter I suppose but I haven't been able to figure out what that pattern would be.
That said, if as outlined above one CAN determine which are going to be those in need a priori and so can order them or divide them out on the initial SAVE of the .mat file, then there certainly would be no reason not to do so to minimize the subsequent LOAD time, but certainly it doesn't seem feasible to have the arbitrary order already and then to try to reorder it. Unless there's some reason to have to LOAD the same variables multiple times, it just doesn't seem likely it would still ever amount to any real bottleneck other than a minor annoyance, perhaps, that it takes a second or so to LOAD that would be nicer if were faster.
I wonder in that case one wouldn't be better off writing a specific i/o function that just dumps a straight binary file instead of using SAVE/LOAD and go with memmapfile or the like instead if there is a real application?
Well, I can't speak for @Paul, but if the reading is done iteratively, the loading can add real overhead. Suppose it's an AI training scenario where your datastore consists of 1000s of .mat files like this, and which must be read in 100s of times...
Well, that was what I have been hoping @Paul could provide just what the use case that generates the issue really is...but in the above why would one knowingly create these .mat files of some thousand or more variables knowing only some very small subset are going to be used? Unless, I suppose, the training were to be redefining which is the desired subset -- in which case, the ordering is probably not going to help anyway as it would seem just as likely to pick one at the tail end instead of the beginning in which case the prior ordering no longer helps -- but, also if only read in some very small subset, how is the training going to know to pick some other specific variable to try unless that is also just random? I just don't see it, sorry...
My testing shows that whos -file reports variables in alphanumeric order regardless of their order in the file.
... I had to use the MATCAT file exchange contribution to prove this.
That's consistent with the display of local variables, yes. Only use I see/saw was to generate the list of wildcard variables in the .mat file if that list weren't already known in order to do the re-creation in a different order -- but, that would still undoubtedly take longer to do than the time that could be saved by doing so...
Files only ned to be created once. But they are used a lot. If each file takes 1 second to load, and there are 100 such files, then one has to sit idly for about 1.5 minutes when the application loops over all of the files, which is long enough to be annoying but not long enough to be prodcutive doing something else. Now multiply that over the course of a session where one runs the application many times while developing, debugging, etc.
Are there other options? Sure. One could, for example, extract the subset of variables from the "parent" files and save them in smaller "child" files. Now we have two sets of files to manage, and those child files may have to be updated as the code is extended to need additional variables from the parent files. And then if someone else comes along to use the same parent files, but their applicatoin requires a wholly different subset, then we have to manage even more child files.
As I was thinking about how to improve things with only one set of files, I realized that there are many dimensions that could influence how fast load works: format, compression, number of variables in the file, number of variables in the subset, and maybe even the classes of tha variables in the file and of the subset (which isn't an issue in this case but could be for others), some of which are controllable at file creation time. Hence the question.
"... extract the subset of variables from the "parent" files and save them in smaller "child" files....two sets of files..."
Alternatively, create a database of the variables with the state of used or not and where stored; each user can have their own database or the user could be a field inside a master. If there were any connections to which variables are somehow related as far as their co- or disparate use, then that could be another segregating tool. If they're all just essentially randomly chosen, that makes such untenable, of course.
As for speed I'd still suggest exploring a pure, flat file structure and direct access. Quite a while back I demonstrated this for another thread that needed lookup in very large files that improved that application by between 10-100X -- I didn't think to save it at the time, but I'll see if I can find it. It might provide alternative ideas.
ADDENDUM
In this case, it might make more sense to keep 26, say, files (one for each starting letter in name, maybe?) and offset in the database. A series of fopen, N*[fseek, fread], fclose would likely outperform LOAD by quite a bit.
@dpb, I'm good for now, so no need to go to any additional effort, unless you think such information would be of general interest to the community ....
OK...as usual, the search was fruitless because don't remember any specific keywords as the subject line as so often didn't really reflect the solution or that the problem would be of a given type...all I recall is that it was a chemical lookup from a massive database that could be converted from serial read to use indexing owing to fixed record size and consequently locate the exact position in the database. Since your example used fixed-size arrays, such logic would work there, too.
Only one other idea I have regarding the debugging iterations and the wait to reload the data -- in that kind of scenario, it might be possible/feasible to save the current working space in a backup .mat file before restarting the app but have a preliminary flag to look for a backup file from which to load the prior workspace -- then might need to only load a new variable or none at all if the input data are unchanged or mostly so....
ADDENDUM
Oh. I did have one other idea to consider -- if the application could stand the difference, saving as single() might cut down the LOAD time noticeably?
Just as comparison --
>> x=rand(1000);
>> save x
>> tic;load x; toc
Elapsed time is 0.051943 seconds.
>> fid=fopen('x.dat','w');
>> fwrite(fid,x);
>> fclose(fid);
>> tic;fid=fopen('x.dat','r');x=fread(fid);fclose(fid);toc
Elapsed time is 0.014438 seconds.
>>
Even w/ the fopen() and fclose() reading 1000x1000 array is 4X as fast as load. That would cut a minute down to 15-20 sec. Would take some rewrite to switch, but if got to be really painful, it's the fastest i/o you'll get.
Even w/ the fopen() and fclose() reading 1000x1000 array is 4X as fast as load.
More like 36X:
x=rand(1000);
save x
fid=fopen('x.dat','w');
fwrite(fid,x);
fclose(fid);
timeit(@() load('x'),1) / timeit(@() binaryReader,1)
ans = 36.3701
function x=binaryReader
fid=fopen('x.dat','r');x=fread(fid);fclose(fid);
end
I realized that there are many dimensions that could influence how fast load works:
format, compression, number of variables in the file, number of variables in the
subset, and maybe even the classes of tha variables in the file and of the subset
For compressed variables, the entire binary representation of the variable data is compressed and stored as a binary blob. Therefore, the class of unused compressed variables does not affect the load time.
The size of the compressed blob has a little effect. A sufficiently small compressed blob fits within the buffer holding the current block, so skipping over it would only require incrementing a pointer into data that has already been read, whereas if the blob is large enough, skipping it requires an fseek() disk operation, which will take variable time (not much time if the file is stored on an SSD.)
A much better test...was lazy and just did the one command line comparison...so, in that case @Paul's 90+/-sec wait time could approach 5 maybe with the extra logic of handling the variables, not just the pure i/o.
Although I guess to be fair, need
N=1000;
x=rand(N);
save x
fid=fopen('x.dat','w');
fwrite(fid,x);
fclose(fid);
timeit(@() load('x'),1) / timeit(@() binaryReader(N),1)
ans = 36.7341
function x=binaryReader(N)
fid=fopen('x.dat','r');x=fread(fid);fclose(fid);x=reshape(x,N,[]);
end
So, the reshape() to get back the 2D array was almost cost-free; only translating from the array to the multiple variables via a struct or cell array to refer to by name would be extra overhead to deal with.
That assumes that compression is applied to each variable independently. Do we know for sure that's how compression works?
There is documentation on version 5 mat files that clearly shows that version 5 mat files contain a header, followed by a series of structured blobs. Compressed variables have a different tag for the variable data, and the data associated with the tag is a binary blob that contains a blob size and zlib 4 compressed data. Variables are clearly compressed independently. The task of loading a particular variable in a mat file consists of first reading the file header, and then traversing the sequence of structured blobs looking for the one with matching variable name, followed by using the blob information to extract the relevant data (which might involve uncompressing data from the binary sub-blob.) As soon as the relevant variable is found, analysis of the file can stop. (Though at the moment I am not sure exactly what happens when an additional variable with the same name is appended to the file; my memory is that the earlier copies of the variables are left intact and so it is necessary to examine all remaining variables in the files just-in-case there is a later version of the variable with the same name.)

Sign in to comment.

More Answers (3)

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
Elapsed time is 0.142189 seconds.
whos s
Name Size Bytes Class Attributes s 1x1 325238 struct
clear s
tic
s = load('matfile.mat'); % load the entire file
toc
Elapsed time is 0.061057 seconds.
whos s
Name Size Bytes Class Attributes s 1x1 8501508 struct
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
Elapsed time is 0.136944 seconds.
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 )
ans = 0.0209
timeit(@() load(fname) ,1)
ans = 0.0564
(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 )
ans = 0.0108
variables = {'v','x'}.'+string(1:20); %scattered variables
timeit(@() load(fname,variables{:}) ,1 )
ans = 0.0101
timeit(@() load(fname) ,1) %all variables
ans = 0.0343
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
ans = 0.0223
ans = 0.1966
ans = 0.0581
compareTimes('-v7.3') % v7.3
ans = 0.0084
ans = 0.0090
ans = 0.0270
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
Would
v=whos(-'file',fname,wildcardpattern);
v={v.name}.';
then pass v resolve that, maybe? Or would the added overhead outweigh any benefit?
I suspect the latter. To resolve the wildcards, whos() has to do the same work traversing the file as load().

Sign in to comment.

@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)
ans = logical
1
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

Thank you very much for the effort. I'll report back if/when I get a chance to try it out. If I do I might modify binarywriter to take in a struct and write the fields directly rather than creating the large temporary 2D array.
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.

Sign in to comment.

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
Let's try out @Matt J test from before...
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))
ans = 5.0797
timeit(@() load(fname),1)/timeit(@() binaryStrucReader(bname,fieldnames(S)))
ans = 5.4843
s=binaryStrucReader(bname,variables); % return the struct to compare
id=randperm(numel(variables),1); % pick a random variable from the list
disp(variables(id))
T1
all(s.(variables{id})==S.(variables{id})) % make sure matches original
ans = logical
1
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

Products

Release

R2024b

Asked:

on 28 Sep 2026

Edited:

dpb
on 8 Oct 2026

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!