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.

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
1  
Try: r[n_] := Symbol["r" <> ToString[n]] –  RunnyKine Dec 12 '13 at 23:14
add comment

2 Answers

up vote 12 down vote accepted
r[n_] := Symbol["r" <> ToString[n]]

Then:

r[1]

gives

r1

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
5  
@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
show 2 more comments

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

share|improve this answer
add comment

Your Answer

 
discard

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.