Code covered by the BSD License  

Highlights from
RenameField

4.0

4.0 | 3 ratings Rate this file 24 Downloads (last 30 days) File Size: 9.46 KB File ID: #28516
image thumbnail

RenameField

by

 

20 Aug 2010 (Updated )

Rename a fields of a struct - fast C-Mex

| Watch this File

File Information
Description

RenameField - Rename a fields of a struct

T = RenameField(S, Old, New)
INPUT:
  S: Struct or struct array.
  Old: String or cell string, name of the field to be renamed.
  New: String or cell string, new field name, which must be a valid Matlab symbol.
OUTPUT:
  T: Struct S with renamed fields.

EXAMPLES:
  S.A = 1; S.B = 2;
  T = RenameField(S, 'B', 'C'); % >> T.A = 1, T.C = 2

This function was created after a discussion in Loren's blog:
  http://blogs.mathworks.com/loren/2010/05/13/rename-a-field-in-a-structure-array

Tested: Matlab 6.5/2009a, WinXP 32 bit, LCC2.4/3.8, BCC5.5, OpemWatcom 1.8, MSVC 2008
Compatibility to 64 bit, Linux, MacOS is assumed.

Look in the C-file for instructions to compile the Mex file at first.
A slower M-version is included, but disabled by a call to ERROR. The M-version does not check the validity of the new names.

MATLAB release MATLAB 7.8 (R2009a)
Tags for This File   Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (6)
19 Sep 2011 Jan Simon

@Renan: I cannot find an intuitive input syntax for considering subfields. E.g. using nested cells would increase the complexity of the function and of the caller, such that bugs becomes more likely.
It would be nicer and simpler to create an M-function, which calls RenameField recursively.

19 Sep 2011 Renan

Very nice work! Exactly what I was looking for.

One suggestion: Could you change your script such that it renames all the subfields (fields within fields, e.g., S.field1.field2) in a structure?

14 Feb 2011 Jan Simon

@Matthew: Thanks for the rating. Do you have a suggestion for any improvements?

13 Feb 2011 Matthew  
06 Feb 2011 Jan Simon

@Michael: Thanks for the comments. In the comment section of the C-file you find instruction for considering the C99 style comments with GCC under Linux. The C99 standard is 12 years old and the default for MSVC, LCC, OpenWatcom, BCC and ICC. I don't know, why the -std=c99 flag is not included as default in Matlab's Mex-options file of the GCC, but it is much better to write an improvement request to TMW, than to want FEX submissions to be formatted according to a 22 year old standard. BTW: You can rename the file to .cpp also.
The cell string input is a nice idea and I'll insert it soon.

06 Feb 2011 Michael

This function is exactly what I was looking for, since it preserves the original ordering! Great!

Even though I did not manage to compile the mex file due to the c++ comment style...

The function would be even better, if it would take also cell arrays for the old and new fieldnames.

Updates
13 Feb 2011

Accept cell strings as input.

Contact us