MATLAB Answers

How can I load a field from a saved structure?

354 ビュー (過去 30 日間)
K E
K E 2016 年 5 月 5 日
コメント済み: K E 2016 年 5 月 6 日
For my work, it is convenient to store measurement data in structures with many fields. The structure is useful for keeping all the measurements together, passing into functions that plot everything, etc. However the files get large and bulky to handle. I'd like to be able to load a specified field from the *.mat file containing the structure. I thought this was possible using this approach (saving with -struct flag), but only separate variables containing the fields are saved and the original structure is lost. Is there a way to retrieve a field out of an existing mat file containing a structure, as is shown below, perhaps using matfile ?
% Make the structure
a.Temperature.value = rand(1,10);
a.Temperature.units = 'C';
a.Humidity.value = rand(1,10);
a.Humidity.units = '%';
save('c:\temp\junk.mat', 'a'); % Save the structure
load('c:\temp\junk.mat', 'a.Temperature'); % Load a specified field (doesn't work)

  0 件のコメント

Sign in to comment.

採用された回答

Adam
Adam 2016 年 5 月 5 日
編集済み: Adam 2016 年 5 月 5 日
save('c:\temp\junk.mat', '-struct', 'a');
load('c:\temp\junk.mat', 'Temperature');
should work I think. Or
loadedVars = load('c:\temp\junk.mat', 'Temperature');;
Temperature = loadedVars.Temperature;
if you prefer.

  3 件のコメント

K E
K E 2016 年 5 月 5 日
I was grumpy about the fact that the -struct file results in a mat file containing variables, i.e. I lose the original structure, until I realized I could regain it as shown below. However we have tons of already-saved *.mat files containing large structures which I would love to pull fields out of but sounds like that is not an option.
save('c:\temp\junk.mat', '-struct', 'a');
a = load('c:\temp\junk.mat');
% Has fields a.Temperature and a.Humidity
Adam
Adam 2016 年 5 月 6 日
Yes, it seems even using the matfile function this cannot be done (as also indicated on its help page):
>> mFile = matfile( 'c:\temp\junk.mat' );
>> mFile.a.Temperature
Cannot index into 'a' because MatFile objects only support '()' indexing.
K E
K E 2016 年 5 月 6 日
I have put in a request to add the ability to load fields in future releases.

Sign in to comment.

その他の回答 (0 件)


Translated by