Renaming tags in an array of structures [message #72550] |
Thu, 16 September 2010 11:28 |
Michael Williams
Messages: 17 Registered: December 2008
|
Junior Member |
|
|
I have an array of structures:
IDL> x = {a: 1, b:2, c: indgen(5)}
IDL> xx = replicate(x, 10)
In this case, I want to rename the 'b' tag to 'foo' and the 'c' tag to
bar. But I want a function that works for arbitrary tag names. I have
read http://www.dfanning.com/code_tips/addfield.html, which describes
how to add a field to an array of structures using struct_assign. So
far I have the following function, which seems like it's headed in the
right direction: it will add the foo and bar tags. But (i) it only
works if you're renaming exactly two tags because of the create_struct
call (ii) it doesn't copy the data in the old tags to the new tags and
(iii) it doesn't delete the old tags, which is necessary for true
"replacement".
Can anyone see how to fix these problems so that the function works
for arbitrarily many tag names, copies the data (ideally without using
execute statements, which is the only way I can think of doing it),
and the old fields are deleted? Or is there another solution
altogether?
function add_field_array_str, str, old_tags, new_tags
template = create_struct(new_tags, 0., 0., str[0])
newstr = replicate(template, n_elements(str))
struct_assign, str, newstr
; Copy the contents of "str.old_tags" to "newstr.new_tags" ... ?
; Delete "newstr.old_tags" ... ?
return, newstr
end
IDL> xx2 = add_field_array_str(xx, ['foo', 'bar'])
IDL> help, xx2, /struct
** Structure <1a17494>, 5 tags, length=24, data length=22, refs=1:
FOO FLOAT 0.00000
BAR FLOAT 0.00000
A INT 1
B INT 2
C INT Array[5]
|
|
|