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

I have three variables like this,

r1 = 4;
r2 = 3;
r3 = 1;

and I want to insert them into a function use them in a function definition like so:

f[n_] := r[n] + r[n-1]

So I need to have a function that just duplicates the variable, something like:

r[1] = r1 = 4;
r[2] = r2 = 3;
r[3] = r3 = 1;

Firstly, I thought of doing

r[n_] := r[n]

but that doesn't make much sense.

I was wondering if there is some nice way to do this?

share|improve this question
Try: r[n_] := Symbol["r" <> ToString[n]] – RunnyKine Dec 12 '13 at 23:14
up vote 12 down vote accepted
r[n_] := Symbol["r" <> ToString[n]]





share|improve this answer
But is r[1]=r1=4 true? – Arcotick Dec 12 '13 at 23:30
@Arcotick r[1] == r1 == 4 will evaluate to True – Jacob Akkerboom Dec 12 '13 at 23:38
+1 for correctly using Symbol instead of ToExpression. – Mr.Wizard Dec 13 '13 at 1:50
To @Mr.Wizard, why not ToExpression? I thought the effect is the same... – Leo Fang Dec 13 '13 at 3:31
@Leo The effect can be the same, but ToExpression will also evaluate arbitrary code which could result in strange errors, or in the case of library code malicious abuse. Symbol is simply better suited yet often overlooked. Evaluation is somewhat different as well (as shown by Trace) but usually not significant. – Mr.Wizard Dec 13 '13 at 3:41

The method below sets the actual values to r:-

r1 = 4;
r2 = 3;
r3 = 1;

Clear[r, f, g];

f = Function[{rn},
   r[ToExpression@StringDrop[ToString@Unevaluated[rn], 1]],

g = Function[{rf}, Evaluate[f[rf]] = rf, {HoldFirst, Listable}];

g[{r1, r2, r3}]

{4, 3, 1}

r[1] == r1


share|improve this answer

Your Answer


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.