Переименуйте несколько полей в структуре MATLAB

Мне нужно переименовать кучу полей в структуре, в основном изменив префикс на ней.

e.g.

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

to

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

не печатая по одному...так как их много и может расти.

Спасибо!


person Aeson    schedule 11.02.2013    source источник


Ответы (1)


Вы можете сделать это, динамически генерируя имена полей для выходной структуры.

% 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;
person Praetorian    schedule 11.02.2013
comment
Спасибо! Работал как шарм! - person Aeson; 12.02.2013