Making a function recursive [message #51622] |
Sat, 02 December 2006 11:56 |
Brian Larsen
Messages: 270 Registered: June 2006
|
Senior Member |
|
|
All,
I have been doing this for years and just wanted a bit of input from
others as to if this the best way, possible dangers, another way, and
all of this approach which does work. I don't recall exactly if this
method came from my brain or another source so if you recognize it let
me know that too.
The situation is you have a routine that can only operate on scalar
input but you really want to put a vector into it. One example is
reading a bunch of files from findfile() into a structure array or the
like.
Here is a toy example that could undoubtedly be rewritten without this
trick but there are others that cannot and follow the same template so
this is short and will demonstrate the method.
-----------------
function jd2string, jd
;; check to see if this called with an array input
;; and if so do this recursively
IF N_ELEMENTS(jd) GT 1 THEN BEGIN
;; get one answer so I don't have to know the return type or
structure tags
ans = jd2string(jd[0])
;; replicate it so it is the same size as the input
ans = replicate(ans, N_ELEMENTS(jd))
;; run through and do the operation on each element in the input
array
FOR i=1l, N_ELEMENTS(jd)-1 DO BEGIN
tmp = jd2string(jd[i])
ans[i] = tmp
ENDFOR
;; this is a vector answer from the vector input
return, ans
ENDIF
;; this can be any function that only works on a scalar as written
caldat, jd, m, d, y, h, m
doy = fix(jd - julday(1, 1, y, h, m) + 1)
return, zeropad(y, 4) + "/" + zeropad(doy, 3) + "/" + zeropad(h, 2) +
":" + $
zeropad(m, 2)
end
------------------------
here is a bit to test it so you don't have create a bunch of julian day
values
IDL> times = [2452079.0, 2452079.1, 2452079.2, 2452079.3, 2452079.4]
IDL> print, jd2string(times)
2001/168/12:00 2001/168/12:00 2001/168/18:00 2001/168/18:00
2001/169/00:00
Thanks for any advice,
-Brian
------------------------------------------------------------ ---------------
Brian A. Larsen
Dept. of Physics
Space Science and Engineering Lab (SSEL)
Montana State University - Bozeman
Bozeman, MT 59717
|
|
|