# Automatically compute r[1] = r1; r[2] = r2; …

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?

-
Try: r[n_] := Symbol["r" <> ToString[n]] – RunnyKine Dec 12 '13 at 23:14

r[n_] := Symbol["r" <> ToString[n]]


Then:

r[1]


gives

r1

-
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]],
{HoldFirst}];

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

g[{r1, r2, r3}]


{4, 3, 1}

r[1] == r1


True

-