13

I have a large structure in a MAT-file. I want to check if a specific field is present in the structure without loading the MAT-file since the contents are very large and I want to minimize memory use.

Is this possible, or must I load it first like in the following example?:

load('test.mat');             %# Load the MAT-file
tf = isfield(s,'fieldname');  %# Check if structure s has field 'fieldname'
gnovice
  • 125,304
  • 15
  • 256
  • 359
Elpezmuerto
  • 5,391
  • 20
  • 65
  • 79

2 Answers2

23

To check the contents of a MAT file without loading it, use:

vars = whos('-file','test.mat')
ismember('fieldname', {vars.name})
Amro
  • 123,847
  • 25
  • 243
  • 454
  • @Jonas: The above code only checks for variable names. So like you mentioned in your answer, the user should use the `-struct` option of SAVE to split the structure fields into separate variables when saving to a MAT-file. – Amro Oct 26 '10 at 18:48
  • 2
    @Jonas: otherwise, and if the user is really concerned about memory use, we can simply write the fieldnames to a separate text file along with the actual MAT-file, then load and check the text file as needed before loading the actual structure data – Amro Oct 26 '10 at 18:55
  • You could also save the list of field names (or other metadata) in a separate variable inside the same .mat file as the original struct, (e.g. with "fnames=fieldnames(s);save('myfile.mat','fnames','s')") and then selectively read it with the "load(filename, varname)" form. Could simplify file management by keeping the data and index in a single file. Amro's method of splitting into separate variables will also let you selectively load parts of the struct; this one won't. And if you have big cellstr arrays in there, convert them to char before saving if possible. Can save both space and time. – Andrew Janke Oct 26 '10 at 20:26
6

As far as I know, you have to load the file in order to be able to check if a saved structure contains a specific field.

However, if you save the .mat file with the '-struct'-option, it splits the fields into separate variables in the .mat file. You can recreate the structure by calling

myStructure = load('test.mat');

Saving this way also allows you to test for whether a field (variable) exists by using @Amro's approach (which is a lot cleaner than what I suggested before).

Community
  • 1
  • 1
Jonas
  • 74,690
  • 10
  • 137
  • 177