Renaming Field Names of a Struct
43 views (last 30 days)
Show older comments
I have a struct array and I want to create a new one out of it.
I fetch the old name through
fieldnames
and I will only have to add 'AA_'
Example:
old Fieldname: Angle
new Fieldname: AA_Angle
Heres an example:
for ii = 1:dim2(1)
fName2 = (fieldnames(tmp.(fName)));
check_struct = isstruct(tmp.(fName).(fName2{ii}));
if check_struct == 1
dim3 = size(fieldnames(tmp.(fName).(fName2{ii})));
for iii = 1:dim3(1)
fName3 = (fieldnames(tmp.(fName).(fName2{ii})));
if isequal(fName3{iii},'Name')
value = getfield(tmp,fName,fName2{ii},fName3{iii});
novalue = isempty(value);
if novalue == 1
newfile.(fName2{ii}).(fName3{iii}) = fName2{ii}; %% Here the newfile is created and fName2 schould already be with 'AA_....'
end
end
end
end
end
Any help is appreciated.
0 Comments
Answers (1)
Voss
on 8 Apr 2022
If you want to rename the fields of a struct array, you can do so like this:
S = struct('field_1',{1 2},'field_2',{3 4})
str = 'AA_';
f = fieldnames(S);
f_new = strcat(str,f);
for jj = 1:numel(S)
for ii = 1:numel(f)
S(jj).(f_new{ii}) = S(jj).(f{ii});
end
end
S = rmfield(S,f)
However, it looks like (maybe?) you want to not only rename the fields of a struct but also rename the fields of any struct that is a field of that struct and so on and so forth ad infinitum. If that's the case you can do so with a recursive function.
S = struct( ...
'field_1',9, ...
'field_2',{{1 2}}, ...
'field_3',struct( ...
'sub_field_1',[11 12 13], ...
'sub_field_2',{14 15}));
S_new = prepend_field_names(S,'AA_');
S, S_new
S.field_3, S_new.AA_field_3
S.field_3(1), S_new.AA_field_3(1)
S.field_3(2), S_new.AA_field_3(2)
function S = prepend_field_names(S,str,do_recurse)
f = fieldnames(S);
f_new = strcat(str,f);
for jj = 1:numel(S)
for ii = 1:numel(f)
S(jj).(f_new{ii}) = S(jj).(f{ii});
if (nargin < 3 || do_recurse) && isstruct(S(jj).(f_new{ii}))
S(jj).(f_new{ii}) = prepend_field_names(S(jj).(f_new{ii}),str,true);
end
end
end
S = rmfield(S,f);
end
0 Comments
See Also
Categories
Find more on Code Execution 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!