Is it possible to extract all fields from a structure automatically?
168 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I have data in the form: mydata.x = 100; mydata.s = 'abc'; mydata.Y = [1 2 3]; And I want variables x = 100; s = 'abc'; Y = [1 2 3]; How to extract variables automatically? (suppose that I don't know the names of the variables!)
7 Commenti
Stephen23
il 14 Nov 2019
Modificato: Stephen23
il 14 Nov 2019
"Why anybody think that this is a dynamic variable in my example?"
Because that is exactly what load does, when called without an output argument: it dynamically creates all of the loaded variables in the caller workspace:
https://www.mathworks.com/matlabcentral/answers/335253-mat-files-not-loading-correctly#answer_262994
And of course:
Risposta accettata
Stephen23
il 11 Ago 2016
Modificato: Stephen23
il 11 Ago 2016
You seem intent on magically making variables pop into existence in the workspace, so here is probably the least-worst way of doing that. The trick is to change the save command by adding the '-struct' option:
>> S.name = 'anna';
>> S.data = 1:3;
>> save('temp.mat','-struct','S')
>> clear
>> load('temp.mat')
>> name
name = anna
>> data
data =
1 2 3
and you will find all of those variables in your workspace.
0 Commenti
Più risposte (3)
Baium
il 14 Nov 2019
Modificato: Baium
il 14 Nov 2019
Alternative, maybe this is more desired than dictating how the struct will be saved in the workspace (this will recursively unpack any struct within the struct):
function unpackStruct (structure)
fn = fieldnames(structure);
for i = 1:numel(fn)
fni = string(fn(i));
field = structure.(fni);
if (isstruct(field))
unpackStruct(field);
continue;
end
assignin('base', fni, field);
end
end
6 Commenti
Alec Jacobson
il 9 Mag 2021
Or as a single anonymous function (which you can drop into your ide)
unpackStruct = @(s) cellfun(@(name) assignin('base',name,getfield(s,name)),fieldnames(s));
Azzi Abdelmalek
il 10 Ago 2016
Modificato: Azzi Abdelmalek
il 10 Ago 2016
Use fieldnames function
mydata.x = 100;
mydata.s = 'abc';
mydata.Y = [1 2 3];
field=fieldnames(mydata)
Then you want to assign to each variable individually a corresponding value, which is not recommended. Read this http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F
0 Commenti
Vedere anche
Categorie
Scopri di più su Performance and Memory in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!