Fast way to check if variable is in .mat file without loading .mat file? 'who'/'whos' is not faster than loading.. Better options than 'who'?

Viewed 1919

I have a .mat file named "myfile.mat" that contains a huge varible data and, in some cases, another variable data_info. What is the fastest way to check if that .mat file contains the `data_info' variable?

the who or whos commands are not faster than simply loading and testing for the existens of varible.

nRuns=10;
%simply loading the complete file
tic
for p=1:nRuns
    load('myfile.mat');
    % do something with variable
    if exist('data_info','var')
        %do something
    end
end
toc

% check with who
tic
for p=1:nRuns
   variables=who('-file','myfile.mat');
   if ismember('data_info', variables)
       % do something
   end
end
toc

% check with whose
tic
for p=1:nRuns
   info=whos('-file','myfile.mat');
   if ismember('data_info', {info.name})
       %do something
   end
end
toc

All methods roughly take the same time (which is way to slow, since data is huge.

However, this is very fast:

tic
for p=1:nRuns
    load('myfile.mat','data_info');
    if exist('data_info', 'var')
        %do something
    end
end
toc

But it issues a warning, if data_info does not exist. I could suppress the warning, but that doesn't seem like the best way to do this.. What other options are there?

Edit using who('-file', 'myfile.mat', 'data_info') is also not faster:

tic
for p=1:nRuns
    if ~isempty(who('-file', 'myfile.mat', 'data_info'))
      % do something
    end
end
toc    % this takes 7 seconds, roughly the same like simply loading complete .mat file
3 Answers

So its a bit messy, but I just tried this and its pretty much instant regardless of size. Let me know if it works for you.

Please excuse the formatting, im not used to proper formatting here.

Note: This solution uses low level HDF5 libraries that are already built into matlab, so this method assumes your mat file is HDF5 (-v7.3). Otherwise it will not work.

You can be sure is a valid hdf5 file by doing this:

isValidHDF = H5F.is_hdf5('my_file.mat');

To see if your variable exists:

isThere = false; %Initialize as default value of false
fid = H5F.open('myfile.mat') % Use low level H5F builtin to open
try % Never use try/catch but this is a good for when its ok
     % Try to open the h5 group. Will error and catch to report back false if the variable isnt there, otherwise the variable exists
     gid = H5G.open(fid,['/data_info']); % Note: the "/" is required and OS independent, so its never "\" even in windows

     % I think this makes sure the variable isnt empty if the group opened successfully, but it hasnt been a problem yet
     hInfo = H5G.get_info(gid); 
     isThere = hInfo.nlinks > 0;
     H5G.close(gid);
end
H5F.close(fid);
Related