给定一个结构体数组,如何重命名其中的一个字段?比如,针对以下结构体,如何将“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)
什么是最佳方法,其中“最佳”是性能、清晰度和通用性的平衡?
给定一个结构体数组,如何重命名其中的一个字段?比如,针对以下结构体,如何将“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)
什么是最佳方法,其中“最佳”是性能、清晰度和通用性的平衡?
rmfield
的方法来实现它:[a.baz] = a.bar;
a = rmfield(a,'bar');
disp(a)
[a(:).baz] = deal(a(:).bar);
,但 SCFrench 指出 deal
是不必要的。以下是使用struct2cell/cell2struct的方法:
f = fieldnames(a);
f{strmatch('bar',f,'exact')} = 'baz';
c = struct2cell(a);
a = cell2struct(c,f);
disp(a)