MATLAB: How to dynamically extract fields from a structure and create variables in the MATLAB workspace using the field names

decomposeextractfieldfieldsMATLABnamesstructstructurevariableworkspace

I have a created a structure containg fields a, b and c. Now I want to decompose my structure and save a, b and c as workspace variables with the filed name as the variable name.

Best Answer

One possibility to dynamically decompose your struct would be using FIELDNAMES command to determine the fields and create according variables using EVAL, like in the following example:
constants.a = 4;
constants.b = 8;
constants.c = 10;
names = fieldnames(constants);
for i=1:length(names)
eval([names{i} '=constants.' names{i} ]);
end
In case of nested structures, you can use nested FOR loops to access the fields.
constants.a.aa=4;
constants.a.ab = 5;
constants.b = 8;
constants.c = 10;
names = fieldnames(constants);
for i=1:length(names)
if isstruct(eval(['constants.' names{i}]))
names2 = fieldnames(eval(['constants.' names{i}]));
for j=1:length(names2)
eval([names{i} '_' names2{j} '=constants.' names{i} '.' names2{j}]);
end
else
eval([names{i} '=constants.' names{i} ]);
end
end