Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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)

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., R. M. Jan 13 '14 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 '14 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 '14 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 '14 at 4:11

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

SetAttributes[assign, HoldFirst];

assign[z_] := z = 2

a = 1;

{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

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