How do I rename fields of a structure array?
Mostrar comentarios más antiguos
Say I have a structure array such as
A =
1x49 struct array with fields:
a
b
c
d
How do I rename the structure fields? Such as
A =
1x49 struct array with fields:
aa
ba
ca
da
4 comentarios
Eduardo
el 6 de Mayo de 2020
Dear MATLAB reps, I hope that the myriad of workarounds from user answers for something that should be extremely simple prompts you to do something about your product. It's the little things.
Rhys Williams
el 10 de Ag. de 2022
I second that!
Leon
el 7 de En. de 2024
I third it.
Steven Lord
el 9 de En. de 2024
Editada: Steven Lord
el 9 de En. de 2024
To officially submit this as an enhancement request please contact Technical Support directly using this link. When you do, please mention the circumstances in which you'd want to use this functionality if it existed.
- Would you need it to support non-scalar struct arrays?
- Would you need it to be able to rename one field at a time or renaming a collection of fields all at once?
- How would you expect it to operate if you tried to rename a field to a field name that already exists in the struct? Error, warn and do nothing, overwrite, try to merge them somehow, etc.?
- Do you need it to be able to operate over multiple levels? If you had a struct a with fields b and c where b was itself a struct array with field d, would you expect to be able to change both a.c and a.b.d in one call (assuming the answer to my second question was "renaming a collection of fields all at once")?
Respuesta aceptada
Más respuestas (7)
Jos (10584)
el 17 de Mzo. de 2016
There is a somewhat hidden function called renameStructField, that can do the job, perhaps within a loop.
Or use dynamic field names and copy the fields into a new structure. This makes code quite readable and bug proof.
oldnames = {'a','b','c'}
newnames = {'aa','test','cXY'}
for k=1:number(oldnames)
Snew.(newnames{k}) = Sold.(oldnames{k}) ;
end
3 comentarios
Jos (10584)
el 17 de Mzo. de 2016
btw, since you have a structure array, the various solutions offered to you might need some tweaking ...
John Petersen
el 17 de Mzo. de 2016
Jos (10584)
el 18 de Mzo. de 2016
Use deal (see my other answer)
Sriram Nayak
el 18 de Abr. de 2020
Editada: Walter Roberson
el 6 de Mzo. de 2024
function structOut = renamefield(structIn, oldField, newField)
for i = 1:length(structIn)
structIn = setfield(structIn,{i},newField,getfield(structIn(i),oldField));
end
structOut = rmfield(structIn,oldField);
end
1 comentario
Walter Roberson
el 6 de Mzo. de 2024
This will fail if the new field names happen to include some of the old field names. For example
a -> aa
b -> a
Jos (10584)
el 18 de Mzo. de 2016
You can use DEAL and a for-loop to change fieldnames:
% create a structure array, with different fields
for k=1:10,
Sold(k) = struct('a',k,'b',1:k','c',sprintf('test%02d',k)) ;
end
% engine
oldnames = {'a','b','c'}
newnames = {'aa','test','cXY'}
N = numel(Sold)
for k=1:numel(oldnames)
[Snew(1:N).(newnames{k})] = deal(Sold.(oldnames{k})) ;
end
Teresa Martinez
el 26 de Mayo de 2021
0 votos
Create new fields with the same data:
A.aa = A.a;
A.ba = A.b;
and remove the old ones:
A = rmfield(A,'a');
A = rmfield(A,'b');
1 comentario
Aditya
el 11 de Mzo. de 2023
Won't work for non scalar parameters
Jan
el 8 de Jun. de 2022
0 votos
Although this thread is old, it has a lot of views and it is worth to mention this implementation as fast C-Mex:
Until Matlab (hopefully) introduces a rename field function, I would convert to a table then use renamevars() and then convert back to a struct. E.g., where S is your struct:
T = struct2table(S);
T = renamevars(T, 'Old_Name', 'New_Name');
S = table2struct(T);
Or, as one line:
S = table2struct(renamevars(struct2table(S), 'Old_Name', 'New_Name'));
An advantage of this over converting to a cell array and back is that you don't need to worry about the names of the other fieldnames, or know what number the field is, etc. You can still rename several fields at once when using renamevars. Also, since each variable in a Matlab table has to maintain the same value for all rows, it should be much more efficient memory-wise than converting a large struct into a cell array and back (where each cell can be of any type and that type must be stored), but I haven't done any tests.
Actually, once you have converted to a table, you may want to have a good think about whether it makes sense to convert it back into a struct: it is often more comfortable to work with tables, and they can be more efficient memory-wise. Apart from better memory use and functions like renamevars, there are neat features like being able to have several variable names under one column.
Or try the C-Mex "renamefield" on Matlab file exchange, as Jan suggested.
5 comentarios
Note that this is not a general solution.
For non-scalar structures the field data will (generally) be concatenated together (e.g. for numeric, string, char types). If the structure elements have different data types for the same field, then they will be converted following the usual MATLAB rules when concatenating different data types, i.e. there is the risk of loss of data without any warning, as shown here:
S = struct('X',{uint8(1),realmax},'Y',{uint8(2),Inf},'Z',{"string",pi})
T = struct2table(S) % oops, where did my data go?
For more information:
Leon
el 23 de Feb. de 2024
Wow. I'm surpised Matlab isn't smart enough to just keep the columns as cell type. That's worrying.
@Leon: The only cell arrays were the ones used as inputs to the struct() function, and that's done so that struct() produces a non-scalar struct array output. The data contained in the resulting struct array is all numeric or string, not cell arrays.
S = struct('X',{uint8(1),realmax},'Y',{uint8(2),Inf},'Z',{"string",pi})
S(1) % no cell arrays here
S(2) % none here either
T = struct2table(S) % oops, where did my data go?
If you want a struct array containing cell arrays you can do that
S = struct('X',{{uint8(1)},{realmax}},'Y',{{uint8(2)},{Inf}},'Z',{{"string"},{pi}})
S(1)
S(2)
And in that case struct2table does keep them cell arrays:
T = struct2table(S)
class(T.X)
So there's nothing to worry about.
Stephen23
el 9 de Mzo. de 2024
"I'm surpised Matlab isn't smart enough to just keep the columns as cell type."
They aren't cell type.
Leon
el 9 de Mzo. de 2024
I see. Thanks.
Ethan Montag
el 14 de Mayo de 2024
If you open the structure to view in a window, you can manually change the name ot the field manually by double clicking on it.
When you do this, the code that produced the change is shown in the Command Window:
[structName.newName] = structName.oldName;
% This adds a new field, newName, with the same data as in the field oldName
structName = orderfields(structName,[1:3,12,4:11]);
% In this example, there are 11 fields and I changed the name of the 4th field.
%This command reorders the new field into the place of the old field.
structName = rmfield(structName,'oldName');
% This removes the old field
Categorías
Más información sobre Data Type Conversion en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!