Re: Calling functions with huge arguments
- To: mathgroup at smc.vnet.net
- Subject: [mg97657] Re: Calling functions with huge arguments
- From: ragfield <ragfield at gmail.com>
- Date: Wed, 18 Mar 2009 04:52:42 -0500 (EST)
- References: <gpns8b$gkh$1@smc.vnet.net>
On Mar 17, 4:58 am, Fernando Cucchietti <fernando.cucchie... at icfo.es>
wrote:
> I am working with a VERY large tensor, so much that I would like to
> keep at most two copies of it in memory at any given time. The
> algorithm I want to run is convoluted and repetitive, but it looks
> very compact when written in terms of subroutines and functions that
> call themselves many times. However, from what I gather, Mathematica
> effectively creates a copy of the arguments when a function is called. =
> Is this correct?
> If so, I need to find a way to mimic pass-by-reference style as in C
> or Fortran, or just pass the arguments that are not big and keep my
> tensors defined globally (which I think makes the code look less
> nice). Unwrapping the code so that it does not call functions is not
> an option, because it would be very complex and never-again-usable.
> My main question is then: what are the best ways to do pass-by-
> reference (if it is better than global naming), or what approaches
> have you taken to overcome similar problems?
I don't know whether this solves your problem or not, but you can sort
of fake "pass by reference" behavior by giving your subroutine a Hold*
(HoldAll/HoldFirst/HoldRest) attribute. This way the subroutine has
access to the symbol you pass in and it can make changes in place.
In[1]:= Attributes[MyFunc] = HoldAll;
In[2]:= MyFunc[a_Symbol] := (a[[2]] = 2.2);
In[3]:= b = {1., 2., 3., 4.}
Out[3]= {1., 2., 3., 4.}
In[4]:= MyFunc[b];
In[5]:= b
Out[5]= {1., 2.2, 3., 4.}
-Rob