[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Multiple values from a function?



Simon de Vet wrote:
> 
> I have a function that does a whole lot (it started out as an
> independent program). It works very well when returning one of it's
> calculated arrays.
> 
> It also produces a number of other arrays which I'd like to have access
> to.  Unfortunately, I have discovered that a function can only return
> one value.
> 
> How can I get the other arrays out of it? The code is intertwined, so it
> would be hard to break into 2 or 3 independent functions.
> 
> Concatenation of arrays is not an option, since they are all of
> different sizes.  I can get around the problem by doing the calculation
> in the main level program instead of in a function, but that's a little
> ackward. Looking at the help, structures look like a possibility, but I
> don't understand how they work.
> 
> Help!
> 
> Simon


Second alternative: store all your results in a structure. Example:

function mything, in1, in2

   sum=in1+in2
   diff=in1-in2

   result = { sum:sum, diff:diff }
   return,result
end

You can then access the results as in:
   thunder = mything(5.,20.)
   print,'Sum is : ',thunder.sum,'   Difference is : ',thunder.diff


One addition to Craig's answer: the parameter could also be a keyword,
e.g.
function mything, in, out=out

This is particularily recommended if you judge the output as optional.
In this case
you can use the arg_present function to determine whether output shall
be computed or not:

   ...
   if arg_present(out) then begin
      ;; long-winded computation worth at least 3 trips to coffee maker
      ...
   endif



Cheers,
Martin
-- 
[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
[[ Dr. Martin Schultz   Max-Planck-Institut fuer Meteorologie    [[
[[                      Bundesstr. 55, 20146 Hamburg             [[
[[                      phone: +49 40 41173-308                  [[
[[                      fax:   +49 40 41173-298                  [[
[[ martin.schultz@dkrz.de                                        [[
[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[