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.

This question already has an answer here:

I'm currently trying very hard to assign a variable inside a function.
Therefore I'm using a function like this, which should reassign a predefined variable.

assign[a_] := (HoldForm@a = 2)
a=1;
assign[a]

The problem is that Mathematica uses the value of "a" instead of its name.
Any suggestions?

share|improve this question

marked as duplicate by Leonid Shifrin, Oleksandr R., rm -rf Jan 13 at 3:40

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
You should investigate attributes. Specifically, the ones whose names start with Hold. Alternatively you could perhaps use Unevaluated. But, trying to do the assignment as HoldForm[a] = whatever is not valid since HoldForm is Protected. –  Oleksandr R. Jan 13 at 1:35
    
@LeonidShifrin thanks--I had been looking for a duplicate but didn't succeed in finding it. Actually, I was looking for a different one, but your suggestion is a good match. –  Oleksandr R. Jan 13 at 3:33
    
@OleksandrR. No problem. This seems to be a common question, you are right - there were at least several related discussions here and on SO - and on MathGroup before that. –  Leonid Shifrin Jan 13 at 4:11
add comment

1 Answer 1

As Oleksandr R. commented, you can do this by setting the appropriate attributes, e.g.

SetAttributes[assign, HoldFirst];

assign[z_] := z = 2

a = 1;
assign[a]
assign[b]

{a, b}

(* {2,2} *)

However, there's a reason for scoping rules and constructs, I'd think long and hard before 'circumventing' them, whatever that may mean in your case.

share|improve this answer
add comment

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