【问题标题】:How do I rename a field in a structure array in MATLAB?如何在 MATLAB 中重命名结构体数组中的字段?
【发布时间】:2010-04-28 22:35:51
【问题描述】:

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

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

【问题讨论】:

  • (MathWorks 员工,请参阅 g560416。)

标签: matlab field rename matlab-struct


【解决方案1】:

扩展来自 Matthew 的 this solution,如果新旧字段名称存储为字符串,您也可以使用 dynamic field names

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 您不需要在第一行进行交易。你可以使用 [a.baz]=a.bar;
    • 更好!我会修改这个答案。
    【解决方案3】:

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

    f = fieldnames(a);
    f{strmatch('bar',f,'exact')} = 'baz';
    c = struct2cell(a);
    a = cell2struct(c,f);
    disp(a)
    

    【讨论】:

    • 函数 rmfield.m 正是这样做的。关于性能 rmfield 非常慢。通常你不需要重命名结构中的字段。
    • 我没有意识到 rmfield 是在 MATLAB 代码中实现的。是的,它正在做一些非常相似的事情。谢谢指点。
    猜你喜欢
    • 2016-05-04
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 2023-01-27
    相关资源
    最近更新 更多