How can I load a field from a saved structure?

283 vues (au cours des 30 derniers jours)
K E
K E le 5 Mai 2016
Commenté : Utku Arslan le 26 Fév 2021
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)

Réponse acceptée

Adam
Adam le 5 Mai 2016
Modifié(e) : Adam le 5 Mai 2016
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.
  4 commentaires
K E
K E le 6 Mai 2016
I have put in a request to add the ability to load fields in future releases.
Utku Arslan
Utku Arslan le 26 Fév 2021
I gotcha bro!
function importfile(fileToRead1)
%IMPORTFILE(FILETOREAD1)
% Imports data from the specified file
% FILETOREAD1: file to read
% Import the file
newData1 = load('-mat', fileToRead1);
% Create new variables in the base workspace from those fields.
vars = fieldnames(newData1);
for i = 1:length(vars)
assignin('base', vars{i}, newData1.(vars{i}));
end
peace out, much love. -KP

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Debugging and Analysis dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by