tags:

views:

65

answers:

2

I have a large struct in a .mat file. I want to check if a specific field is present in the struct without loading the .mat file. The .mat files are very large and I want to minimize memory use.

Can I do this or must I use the I load it like this? Suppose the .mat file is called "test.mat" with struct s in it:

load('test.mat')
tf = isfield(s, 'fieldname')
+3  A: 

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).

Jonas
+7  A: 

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

vars = whos('-file','test.mat')
ismember('fieldname', {vars.name})
Amro
@Amro: Does that work for fields of structures inside `test.mat`?
Jonas
@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
@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
@Amro: Good point.
Jonas
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

related questions