I have a list of variables:
{RBI,RCD,ASD,FGH}
I want to select only those whose name starts with R. Using the pattern Rx_ does not work because it takes the Rx all together, so all variables in the list get selected.
I have a list of variables:
{RBI,RCD,ASD,FGH}
I want to select only those whose name starts with R. Using the pattern Rx_ does not work because it takes the Rx all together, so all variables in the list get selected.
If it's absolutely necessary to use the symbols as you've defined them, here's one option. (I've added FRH to the list to show that it doesn't get matched.)
Cases[{RBI, RCD, ASD, FGH, FRH}, a_ /; StringMatchQ[ToString @ a, "R" ~~ ___]]
results in
{RBI, RCD}
which is a list of Symbols (not a list of Strings).
Now, there's a problem if you have already assigned values to these symbols. For instance, if RBI = 1, then the command above returns
{RCD}
because Cases evaluates its first argument before matching the pattern in the second argument. I don't know how to fix this problem, which is why I suggest:
I agree with the comments: try to name your variables differently. Perhaps something like R[BI] or R[C][D]. Then the selection is simple:
Cases[{R[BI], R[CD], A[SD], F[GH], F[RH]}, R[_]]
results in
{R[BI], R[CD]}
Now, if you have already associated values with R, then things won't work, because Cases will evaluate its first argument before matching. For instance, if you have set R[BI] = 1, then the above code results in
{R[CD]}
You would need to modify the code to be
Cases[HoldForm[{R[BI], R[CD], A[SD], F[GH], F[RH]}], R[_], 2]
resulting in
{1, R[CD]}
or
Cases[HoldForm[{R[BI], R[CD], A[SD], F[GH], F[RH]}], R[a_] :> Hold[R[a]], 2]
resulting in
{Hold[R[BI]], Hold[R[CD]]}
You can then ReleaseHold, resulting in
{1, R[CD]}
R[BI] did the trick. Does Mathematica see R[BI] and R[CD] as two different variables though? I checked and the output is different for each (good), but are they really "independent"?
– space_voyager
Jul 24 '15 at 17:38
R[BI] = <stuff> and R[CD] = <things>, then both <stuff> and <things> get associated with the symbol R (look up DownValues and do DownValues[R]), but you can still call them separately. There is also a way to associate <stuff> with BI and <things> with CD rather than R (look up 'UpValues and UpSet).
– march
Jul 24 '15 at 17:43
R[CD] even stronger.
– march
Jul 24 '15 at 18:02
ToString, then use string matching functions. In general, try not to encode information meant to be read programmatically into variable names. It's error prone and considered bad style. It will also be very slow if you proceed to build something big with it ... – Szabolcs Jul 24 '15 at 16:57SymbolName– george2079 Jul 24 '15 at 16:57