Renaming Field Names of a Struct

43 views (last 30 days)
MeitiLuk
MeitiLuk on 8 Apr 2022
Answered: Voss on 8 Apr 2022
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.

Answers (1)

Voss
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})
S = 1×2 struct array with fields:
field_1 field_2
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)
S = 1×2 struct array with fields:
AA_field_1 AA_field_2
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 = struct with fields:
field_1: 9 field_2: {[1] [2]} field_3: [1×2 struct]
S_new = struct with fields:
AA_field_1: 9 AA_field_2: {[1] [2]} AA_field_3: [1×2 struct]
S.field_3, S_new.AA_field_3
ans = 1×2 struct array with fields:
sub_field_1 sub_field_2
ans = 1×2 struct array with fields:
AA_sub_field_1 AA_sub_field_2
S.field_3(1), S_new.AA_field_3(1)
ans = struct with fields:
sub_field_1: [11 12 13] sub_field_2: 14
ans = struct with fields:
AA_sub_field_1: [11 12 13] AA_sub_field_2: 14
S.field_3(2), S_new.AA_field_3(2)
ans = struct with fields:
sub_field_1: [11 12 13] sub_field_2: 15
ans = struct with fields:
AA_sub_field_1: [11 12 13] AA_sub_field_2: 15
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

Categories

Find more on Code Execution in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!