Re: Removing fields from a structure [message #52413 is a reply to message #52409] |
Thu, 01 February 2007 18:48   |
Allan Whiteford
Messages: 117 Registered: June 2006
|
Senior Member |
|
|
M. Katz wrote:
> I was wondering if there's a simple way to remove a field from a
> structure?
>
> I can envision a manual way:
> 0) creating a new structure variable for the result
> 1) reading the original's tag names
> 2) stepping through tag by tag using indexed value references, like a.
> (i)
> 3) using create_struct() to put the tags and values into the new
> structure, one by one, except for the tag(s) we're removing.
>
> Does anyone have a more elegant suggestion?
> M. Katz
>
Sorry, nothing more elegant from me. But here's some code I wrote a
while ago which I think pretty much does what you've suggested.
pro remove_tag,struct,tagname
searchtag=strupcase(tagname)
tagnames=tag_names(struct)
a=[-1]
if n_elements(tagname) eq 1 then a=[a,where(tagnames $
ne searchtag)] else for i=0,n_elements(tagnames)-1 do $
if (where(searchtag eq tagnames[i]))[0] eq -1 then a=[a,i]
if n_elements(a) eq 1 then return
if a[1] eq -1 then return
newstruct=create_struct(tagnames[a[1]],struct.(a[1]))
if n_elements(a) gt 2 then for i=2,n_elements(a)-1 $
do newstruct=create_struct(newstruct,tagnames[a[i]],struct.(a[i ]))
struct=newstruct
end
tagname can be a string or string array. Removing multiple tags by
calling the routine multiple times was a real time overhead which is why
you can give it an array of tags. struct is the input structure which
will be modified on output.
Sorry about the lack of documentation, poor formatting and calling an
important variable 'a'. I never distributed this code - it's still
sitting around waiting to be put in to CVS to replace the old version
which could only do one tag at a time.
The SSW code is probably better and I'm sure the loop gurus can remove
the loops and possibly not call create_struct multiple times which is
the big CPU time overhead.
Thanks,
Allan
|
|
|