4

Given a structure array, how do I rename a field? For example, given the following, how do I change "bar" to "baz".

clear
a(1).foo = 1;
a(1).bar = 'one';
a(2).foo = 2;
a(2).bar = 'two';
a(3).foo = 3;
a(3).bar = 'three';
disp(a)

What is the best method, where "best" is a balance of performance, clarity, and generality?

gnovice
  • 125,304
  • 15
  • 256
  • 359
Matthew Simoneau
  • 6,199
  • 6
  • 35
  • 46

3 Answers3

9

Expanding on this solution from Matthew, you can also use dynamic field names if the new and old field names are stored as strings:

newName = 'baz';
oldName = 'bar';
[a.(newName)] = a.(oldName);
a = rmfield(a,oldName);
gnovice
  • 125,304
  • 15
  • 256
  • 359
4

Here's a way to do it with list expansion/rmfield:

[a.baz] = a.bar;
a = rmfield(a,'bar');
disp(a)

The first line was originally written [a(:).baz] = deal(a(:).bar);, but SCFrench pointed out that the deal was unnecessary.

Matthew Simoneau
  • 6,199
  • 6
  • 35
  • 46
2

Here's a a way to do it with struct2cell/cell2struct:

f = fieldnames(a);
f{strmatch('bar',f,'exact')} = 'baz';
c = struct2cell(a);
a = cell2struct(c,f);
disp(a)
Matthew Simoneau
  • 6,199
  • 6
  • 35
  • 46
  • 2
    Function rmfield.m does exactly this. Regarding performance rmfield is very slow. Usually you do not need to rename field in structure. – Mikhail Poda Apr 29 '10 at 05:30
  • I didn't realize that rmfield is implemented in MATLAB code. Yes, it's doing something very similar. Thanks for the pointer. – Matthew Simoneau Apr 29 '10 at 15:14