A better way to change the name of a structure field?

44 ビュー (過去 30 日間)
Richard Crozier
Richard Crozier 2011 年 3 月 17 日
Hello,
I would like to change the name of a structure field at run time. Specifically, I want to change all the names to upper case. Currently I am achieving this with the following function:
function s = upperfnames(s)
% upperfnames: converts all the field names in a structure to upper case
% get the structure field names
fn = fieldnames(s);
for ii = 1:length(fn)
fname = fn{ii};
% check if the field is already upper case
if ~strcmp(fname, upper(fname))
% if not create an upper case copy of the field
s.(upper(fname)) = s.(fname);
% and remove the original
s = rmfield(s, fname);
end
end
end
The problem here is that I must create a copy of any fields with names which must be changed. According to the whos function as I step through the code, this uses up double the memory required for the field. This could cause problems when I forget about this in a year or two and try to change the name of a structure containing lots of data. Is there a more memory efficient way of doing this?
Thanks,
Richard

採用された回答

Jan
Jan 2011 年 3 月 17 日
You can use the C-mex function published in the FEX: RenameField
F = fieldnames(S);
S = RenameField(S, F, upper(F));
It creates a shared data copy, such that the memory consumption is minimal.
See also: Loren's Blog
BTW: I get exactly these two links on top, if I ask Google for "Matlab rename field".
  2 件のコメント
Richard Crozier
Richard Crozier 2011 年 3 月 17 日
I'd googled things like 'Matlab change structure field name', but not the word 'rename' at any point. That just brought up the matlab doc links which do not have info on this. I'll have to try harder on my google word choices in future :-)
Jan
Jan 2011 年 3 月 17 日
And I will insert your searched words as tags in the FEX page.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeManage Products についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by