Re: variable problems
- To: mathgroup at smc.vnet.net
- Subject: [mg9530] Re: [mg9512] variable problems
- From: David Withoff <withoff>
- Date: Thu, 13 Nov 1997 01:39:58 -0500
- Sender: owner-wri-mathgroup at wolfram.com
> Hello,
> I am I wrote a package on mathematica for strain computations and
> diagrams in mechanics but I have a problem.
>
> Does anyone know how can I modify the value of a parameter of a
> function inside the declaration of the function? Here is an example:
>
> f[x_,y_]:=Module[
> {a1,a2,a3},
> a1=x+y;
> x=1; <------- this line causes an error message ];
>
> Note that I could use a local variable a1 for this putting a line
> a1=x;a1=1; but because of the complexity of the source code i wrote ,
> it's not possible to rewrite every line of code.
>
>
> Thanks you..
>
> If it is possible send me this answer to my email: mtousis at rodopi.cc.du
>
> Manolis Toussis
> Student of the Civil Engineer Department of Democritus University Of
> Thrace.
This can be done by passing x, rather than the value of x, as the
argument to the function f. Mathematica by default passes the value of
x to f, which will lead to errors such as
In[1]:= f[x_]:= Module[{}, x=1]
In[2]:= x = 5;
In[3]:= f[x]
Set::setraw: Cannot assign to raw object 5.
Out[3]= 1
To pass the value of x, it is necessary to prevent x from being
evaluated before it is passed to f. This can be done using
Unevaluated:
In[4]:= x = 5; f[Unevaluated[x]]
Out[4]= 1
or by setting an attributes for f:
In[5]:= SetAttributes[f, HoldFirst]
In[6]:= x = 5;
In[7]:= f[x]
Out[7]= 1
This function makes an assignment to the global value of f. That is,
after evaluating f[x], the global values of x is 1:
In[8]:= x
Out[8]= 1
If you don't want to change the global value of x, then you will
probably want to localize x, as in
In[9]:= f[x_] := Block[{x}, Module[{}, x=1] ]
In[10]:= x = 5;
In[11]:= f[x]
Out[11]= 1
In[12]:= x
Out[12]= 5
Dave Withoff
Wolfram Research