COMPGROUPS.NET | Search | Post Question | Groups | Stream | About | Register

Making a function recursive

• Email
• Follow

```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)
":" + \$
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

-Brian

---------------------------------------------------------------------------
Brian A. Larsen
Dept. of Physics
Space Science and Engineering Lab (SSEL)
Montana State University - Bozeman
Bozeman, MT 59717

```
 0
Reply balarsen (265) 12/2/2006 7:56:31 PM

See related articles to this posting

```Brian Larsen writes:

> 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.

Sort of a loose definition of "vectorize", but hey, whatever
works. :-)

Cheers,

David
--
David Fanning, Ph.D.
Fanning Software Consulting, Inc.
Coyote's Guide to IDL Programming: http://www.dfanning.com/
Sepore ma de ni thui. ("Perhaps thou speakest truth.")
```
 0
Reply news2122 (4023) 12/2/2006 8:09:14 PM

1 Replies
52 Views

Similar Articles

12/13/2013 6:19:40 PM
[PageSpeed]

Similar Artilces:

Rewrite recursive function as non-recursive.
NB -- A copy of this message is also posted in ng: borland.public.delphi.students Hi All, The following function is part of a program which generates a Pascal's Triangle. It uses recursion (as you can see), however, I need a non-recursive version of it. I believe that the technique I'm referring to is called "tail recursion". Can anyone please assist me and rewrite this function so that it does not use recursion (call itself) ??? -- e.g. obviously it would need to use tail recursion, and that's what I'm after. function GetPascalPyramidValue(const X, Y: Integer...

Research in Recursive-to-Non-Recursive Functions
Hi, Can someone please point me to the state-of-the-art research activities for "Automatic Conversion from Recursive to Non Recursive Functions" and such C-to-C Transformations. I have been working for some time on this in the context of C-to-VHDL Conversion. Thanks in Advance, Kaustubh On Monday 29 Nov 2004 4:22 am, Kaustubh wrote: > Can someone please point me to the state-of-the-art research > activities for "Automatic Conversion from Recursive to Non Recursive > Functions" and such C-to-C Transformations. I have been working for > some time on this in the ...

Hi, everybody, The following two functions FACTORIAL and FACTORIAL2, both of which can work very well. Is FACTORIAL F90/F95 Standard conforming? module mod1 contains function factorial(n) implicit none integer :: n, factorial factorial = n * temp(n-1) end function factorial function temp( n ) implicit none integer n, temp if(n == 2) then temp = 2 else temp = factorial( n ) end if return end function temp recursive function factorial2( n ) result( nn ) integer, intent(in) :: n integer :: nn if(n == 2) then nn = 2 else nn = factorial2(n-1...

Make recursion faster...
Hey folks, I'm dissecting a script and found a part of my code that is ridiculously slow. It's a loop to "create" a series a bunch of times and so it involves a recursion. Essentially I have 48 original time series (of different sizes, that's why I'm using cells)..and with each one I want to create B "fake" or bootstrapped series. Here a piece of the script: B = 100; for i = 1:ncountries % ncountries = 48 phis = resultsE{i}.beta; %phis is a 6x1 vector of regression coefficients, calced earlier for b = 1:B ...

recursive nested functions
Hello, I'm writing a compiler for a language that admits recursive nested functions and I am stuck trying to figure out how to handle them. My objective is to lift all nested functions to top level and pass all their free variables explicitly as parameters. For this, I have to figure out which variables are free. So when I'm analyzing the body of each function, I record its free variables. But then obviously when I come across a function call, I have to add _its_ free variables to the list of the enclosing function. You can see how this will loop endlesly if we allow recursive functi...

Recursive SETOF function
I'm trying to port some TSQL to PLPGSQL. The DB has a table with a recursive foreign key that represents a tree hierarchy. I'm trying to re-create a TSQL function that pulls out all the ancestors of a given node in the hierarchy. I'm rather new to PLSQL and I have several questions. 1. In TSQL, I can assign a scalar to the result of query like so: SET @var1 = (SELECT foo FROM bar WHERE bar.uid=@var2) How would I do this in PLSQL? 2. In TSQL the "result table" can be inserted into manually. IE: CREATE FUNCTION foo () RETURNS @ttable TABLE( uid INT...

Applying a function recursively
Hi, I want to apply a "convert" function on an object as follows: If the object is of MyType type, invoke the passed in function. If the object is a dictionary, apply on the keys and values of the dictionary recursively. If the object is a set, list or tuple, apply on each element recursively. Else, leave the object as is. I wrote the following code: def convert(obj, func): if isinstance(obj, MyType): return func(obj) elif isinstance(obj, dict): return dict((convert(key, func), convert(value, func)) for key, value in obj.iteritems()) elif isinstance(obj, (list, ...

how to WRITE(*,*) in a RECURSIVE FUNCTION?
Hi, i use gfortran, a gnu fortran compiler.=20 For debugging it would be usefull if i could write variables to std-out= in a (recursive) function. My compiler denies that. ;-( Any tricks, how i can do it? --=20 mit besten Gr=FC=DFen, Jonas Stein <news@jonasstein.de> =20 Jonas Stein <news@jonasstein.de> wrote: > i use gfortran, a gnu fortran compiler. > For debugging it would be usefull if i could write variables to std-out in a > (recursive) function. > > My compiler denies that. ;-( There is nothing particularly unusual about I/O (to standard ou...

Make function injective
Dear NG, I would like to calculate the inverse function of a (measured) curve which should be strictly decreasing. However, the data is noisy and not 100% perfect. To fix the curve, I've written some lines of code that drop all points that are increasing or level. However, I have the dim feeling that the code could be shorter and more elegant. Any idea how? Thanks, Armin % Fix curve to be injective function isinj = injective(curve) if any(diff(curve(isfinite(curve)))>0) warning('Curve not monotonically decreasing') elseif any(diff(curve(isfinite(c...

recursive function problem
Hi all, I use a recursive function in my code. My data structure is a tree, the tree is composed with branches, and the branch has its name and children. The purpose of this function is to find the branch with a given name. My function is as follows. The problem is that: printf can print the branch with given name during search. but the final return value of the function is always the last branch in the data. That means the recursive function does not stop and return "b" even if the "if" condition is met and "return b" is processed. Would you be kind to help me h...

Recursive iteractive function
Folks, I am implementing a recursive iteractive function that goes through a matrix and finds lines referencing the "caller line", that is, the input of the function is the caller line and then it goes through the matrix finding references to the caller line - the reference is an integer in the second column of the matrix. The problem is that I need to keep the R matrix and the iteraction variable untouched in every instance. Here's what I got: function sweep(caller_line) global A; R=[]; %This is a matrix that will contain a list of lines referencing the caller line ...

Recursive functions #2
I know that this is a trivial problem, but I'm having a hard time solving it with tuby. I could use a little extra help with my programming in ruby skills. The problem I'm faced to solving (taken from a puzzle in a newspaper) is a series of alphabetical triplets like: ubc deg lap pyq ved run pac ken alm mli rnt alg Combining a letter from each triplet, you can form words which will form a sentence (in the above case: 'ugly duckling'). What I want to do is go through all possible permutations of characters, in the triplets, and crossreference them with a dictionary to create...

Renaming recursive functions
Hi, I am a little confused by the behavior of Ypsilon scheme when renaming recursive functions. The problem was encountered when writing a macro to wrap profiling code round an existing function. > (define (a n) (cond ((> 0 n) #t) (else (display n) (a (- n 1))))) > (a 5) 543210#t > (let ((aa a)) (set! a (lambda (n) (display \'start) (aa n) (display \'end)))) > (a 5) start5start4start3start2start1start0startendendendendendende nd The desired result is: start543210end The same result happens in scm. Is this what should happ...

Recursive interpolation function
I'm looking to write a recursive function interpole some values with a table. I put the table values in multi-fields, but now I need to find an easy way to interpole some values. To clarfy wath I mean, I've two multiple field contaning this values: Field A Field B 5000 16,22 7500 14,96 10000 14,12 15000 13,03 20000 12,29 25000 11,76 35000 10,99 50000 10,23 75000 9,43 100000 8,91 150000 8,22 200000 7,76 250000 7,41 350000 6,93...

Recursive functions #2
Hi all, 1)I need your help to solve a problem. I have a function whose prototype is int reclen(char *) This function has to find the length of the string passed to it.But the conditions are that no local variable or global variable should be used.I have to use recursive functions. 2)sizeof(int) is 2 bytes in turboC.It is 4 bytes in case of gcc.why different compilers allocate different amount of memory?what is the reason behind it? Harry wrote: > Hi all, > > 1)I need your help to solve a problem. > I have a function whose prototype is > > int reclen(char *) > >...

javascript recursive appendChild function
Hi all, I am coding an AJAX DHTML whatever application and I was fed up with always typing a lot of appendChild() functions. I created a custom one called append_children() and wanted to share it if anyone need such a function. function append_children() { var a = append_children.arguments; for ( var i = a.length - 1; i > 0 ; i-- ) { try { a[i-1].appendChild(a[i]); } catch(e) { for ( var j = 0; j < a[i].length; j++ ) { append_children(a[i-1], a[i][j]); } } } } You can see a working example with this URL : http://amisphere.blogspot.com/2005/...

Recursively making a copy of a subdirectory..
Hi, I have attached below a script that is supposed to recursively look out for a subdirectory with a particular name & make a copy of the same subdirectory with a new name at the same level as the original level. Unfortunately, its not working for me. Any clues for debugging? Or, is there a simpler way to do the whole thing? Thanks, Ashok ------------------------------------------------------------------------------- #!usr/bin/perl use File::Copy; # start at the top if(\$#ARGV<1) { print "Usage: replace <old-string> <new-string>\n"; exit(-1); } \$new...

calculate a polynomials with a recursion function
i search a programm in matlab to calculate a polynomials with a recursion function as for . "mecatronique mecatronique " <manudi84@gmail.com> wrote in message news:hfbgnb\$8ek\$1@fred.mathworks.com... >i search a programm in matlab to calculate a polynomials with a recursion >function as for . HELP POLYVAL. -- Steve Lord slord@mathworks.com comp.soft-sys.matlab (CSSM) FAQ: http://matlabwiki.mathworks.com/MATLAB_FAQ ...

making onClick dynamic and functional
My task is to change the value of a button and then make it functional with the onClick handler. Changing the value to "Play Again" works, but making the onClick work accordingly does not. The following is a snippet of the script. What is keeping it from working? function displaycards1(){ document.form1.reveal1.value="Play Again"; document.form1.reveal1.onClick="setcards();"; } </script> <form name="form1"> <input id="reveal1" type="button" value="reveal" onClick="which_clicked=this; displaycards1(); re...

list parameter of a recursive function
Hi, I have a function f that calls itself recursively. It has a list as second argument, with default argument equal to None (and not [], as indicated at: http://www.ferg.org/projects/python_gotchas.html#contents_item_6 ) This is the outline of my function: def f ( argument, some_list = None ): if some_list == None: some_list = [] [...] # creation of a new_argument # the function is called recursively only if some condition is respected if some_condition: some_list.append( elem ) f( new_argument, some_list ) # otherwise, we have reache...