Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I need to change a function symbol multiple times by assigning another symbol to it, but when I'm trying to do that the symbols overwrite each other.

I'm assuming this is because the assignment is by reference.

For example, this input:

func1[x_] := x^2
func2 = func1; func3[x_] := func1[x]
{func1, func2, func3}
{func1[#], func2[#], func3[#]} &[4]
func1[x_] := -x
{func1[#], func2[#], func3[#]} &[4]

Gives the following output:

Out[]= {func1, func1, func3}
Out[]= {16, 16, 16}
Out[]= {-4, -4, -4}

How could I make the assignment so changing one function doesn't influence changing the other?

share|improve this question
    
it might well not be the right choice for your problem, but I think you should be aware that for those cases where you treat a function as an object, using Functions is often more appropriate than downvalue-definitions. When using func1=Function[x,x^2] for the first definition and func1=Function[x,-x] for the second your example will work as you want... –  Albert Retey Apr 24 at 13:53
add comment

2 Answers 2

up vote 6 down vote accepted

You should use DownValues (see second Application), with a transformation rule.

Using your code, this input:

In[345]:= func1[x_] := x^2
DownValues[func2] = DownValues[func1] /. func1 -> func2;
func3[x_] := func1[x]
{func1, func2, func3}
{func1[#], func2[#], func3[#]} &[4]
func1[x_] := -x
{func1[#], func2[#], func3[#]} &[4]

Gives the following output:

Out[348]= {func1, func2, func3}
Out[349]= {16, 16, 16}
Out[351]= {-4, 16, -4}
share|improve this answer
    
Nice first answer. +1 –  rasher Apr 24 at 0:12
add comment

The simple way to do it is

func2[x_] = func1[x];

then

func1[x_] := x^2
func2[x_] = func1[x];
{func1, func2}
{func1[#], func2[#]} &[4]
func1[x_] := -x
{func1[#], func2[#]} &[4]

gives

{func1, func2}
{16, 16}
{-4, 16}

Here are links to two valuable answers highly relevant to your problem, Understand what Set (=) really does and Understand the difference between Set (or =) and SetDelayed (or :=)

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.