8
$\begingroup$

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?

$\endgroup$
1
  • 1
    $\begingroup$ Try: r[n_] := Symbol["r" <> ToString[n]] $\endgroup$
    – RunnyKine
    Commented Dec 12, 2013 at 23:14

2 Answers 2

12
$\begingroup$
r[n_] := Symbol["r" <> ToString[n]]

Then:

r[1]

gives

r1

$\endgroup$
7
  • $\begingroup$ But is r[1]=r1=4 true? $\endgroup$
    – Arcotick
    Commented Dec 12, 2013 at 23:30
  • $\begingroup$ @Arcotick r[1] == r1 == 4 will evaluate to True $\endgroup$ Commented Dec 12, 2013 at 23:38
  • $\begingroup$ +1 for correctly using Symbol instead of ToExpression. $\endgroup$
    – Mr.Wizard
    Commented Dec 13, 2013 at 1:50
  • $\begingroup$ To @Mr.Wizard, why not ToExpression? I thought the effect is the same... $\endgroup$
    – Leo Fang
    Commented Dec 13, 2013 at 3:31
  • 6
    $\begingroup$ @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. $\endgroup$
    – Mr.Wizard
    Commented Dec 13, 2013 at 3:41
1
$\begingroup$

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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