I just wrote a recursive function which create a structure nested by the fieldnames given by an array but it doesn't work
Show older comments
if true
% code
function addfield = add(var,fields)
C = {[]};
if numel(fields)>0
k = fields{1};
field = {k};
var = cell2struct(C,field,2);
fields(1)=[];
addfield = var.(k);
add((var.(k)),fields) ;
end
addfield = var;
end end
my idea is to create the structure var and to initiate var.field1.field2.field3...fieldn= [] with fields = {fields1,field2,...,fieldn}
Answers (1)
The simple MATLAB approach is to use SETFIELD() with a comma-separated list:
C = {'f1','f2','f3'};
V = pi;
S = struct();
S = setfield(S,C{:},V);
Checking the structure content:
S.f1.f2.f3
See also:
Categories
Find more on String Parsing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!