Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I rename a field in a structure array in MATLAB?

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?

like image 894
Matthew Simoneau Avatar asked Dec 08 '22 03:12

Matthew Simoneau


2 Answers

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);
like image 83
gnovice Avatar answered Dec 22 '22 01:12

gnovice


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.

like image 31
Matthew Simoneau Avatar answered Dec 21 '22 23:12

Matthew Simoneau