2
$\begingroup$

Let's say I have several variables, named R1, R2 and R3.

I wanted to have a function function[numberOfR_] and I wanted to have the output of the function to be R1 if the entered numberOfR = 1, R2 if the entered numberOfR = 2, etc. I tried defining this function as follows

function[numberOfR_] = "R" + numberOfR_;

but it doesn't put the R and the number together as I hoped; instead, it just gives me

 3+R' or '2+R'

not as a single variable name like R3 or R2. What can I do to solve this?

$\endgroup$
1
  • 4
    $\begingroup$ function[numberOfR_] := Symbol /@ (("r" <> ToString@#) & /@ Range@numberOfR) to give a list of a range, function[numberOfR_] := Symbol@("r" <> ToString@numberOfR) for one-shot - and don't use uppercase initials for your symbols - asking for trouble... $\endgroup$
    – ciao
    Jul 2, 2015 at 5:20

1 Answer 1

2
$\begingroup$

This is your function, but this kind of programming seems to be weird, try other ways to do want you want

f[numberOfR_] := Symbol["R" <> ToString[numberOfR]]
$\endgroup$
1
  • $\begingroup$ This is useful indeed! $\endgroup$
    – apg
    Jun 26, 2019 at 19:49

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