4

给定一个结构数组,如何重命名一个字段?例如,给定以下内容,如何将“bar”更改为“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)

什么是最好的方法,其中“最好”是性能、清晰度和通用性的平衡?

4

3 回答 3

9

扩展 Matthew 的这个解决方案,如果新旧字段名称存储为字符串,您还可以使用动态字段名称:

newName = 'baz';
oldName = 'bar';
[a.(newName)] = a.(oldName);
a = rmfield(a,oldName);
于 2010-04-29T15:54:59.177 回答
4

这是一种使用列表扩展/的方法rmfield

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

第一行原本是写[a(:).baz] = deal(a(:).bar);的,但是 SCFrench 指出deal是不必要的。

于 2010-04-28T22:40:19.417 回答
2

这是使用 struct2cell/cell2struct 的一种方法:

f = fieldnames(a);
f{strmatch('bar',f,'exact')} = 'baz';
c = struct2cell(a);
a = cell2struct(c,f);
disp(a)
于 2010-04-28T22:36:38.247 回答