重命名MATLAB结构中的多个字段

时间:2013-02-11 20:21:33

标签: matlab struct rename field batch-rename

我需要通过基本上改变它的前缀来重命名结构中的一堆字段。

e.g。

MyStruct.your_firstfield
MyStruct.your_secondfield
MyStruct.your_thirdfield
MyStruct.your_forthfield
%etc....

MyStruct.my_firstfield
MyStruct.my_secondfield
MyStruct.my_thirdfield
MyStruct.my_forthfield
%etc...

没有输入每一个......因为有很多并且可能会成长。

谢谢!

1 个答案:

答案 0 :(得分:3)

您可以通过dynamically generating field names为输出结构执行此操作。

% Example input
MyStruct = struct('your_firstfield', 1, 'your_secondfield', 2, 'your_thirdfield', 3 );

% Get a cell array of MyStruct's field names
fields = fieldnames(MyStruct);

% Create an empty struct
temp = struct;

% Loop through and assign each field of new struct after doing string 
% replacement. You may need more complicated (regexp) string replacement
% if field names are not simple prefixes
for ii = 1 : length(fields) 
  temp.(strrep(fields{ii}, 'your', 'my')) = MyStruct.(fields{ii}); 
end

% Replace original struct
MyStruct = temp;