2
$\begingroup$

I have some variables : Subscript[S, 1], Subscript[S, 2]...etc. But they are defined in a for loop like For[g = 1, g < 4, g++, Subscript[S, g] = g]; Later, I need to print each of the variable name, i.e Subscript[S, 1], Subscript[S, 2]...etc. But I can't find a systematic way to do this. For[g = 1, g < 4, g++, Print[HoldForm@Subscript[S, g]]]; doesn't work because it prints Subscript[S, g] always.

Any idea?

Just look at the code:

For[g = 1, g < 4, g++, Subscript[S, g] = g];
Print[Subscript[S, 1]]
Print[Subscript[S, 2]]
Print[Subscript[S, 3]]
For[g = 1, g < 4, g++, Print[Subscript[S, g]]];
Print[HoldForm@Subscript[S, 1]]
Print[HoldForm@Subscript[S, 2]]
Print[HoldForm@Subscript[S, 3]]
For[g = 1, g < 4, g++, Print[HoldForm@Subscript[S, g]]];
For[g = 1, g < 4, g++, Subscript[S, g] =.];

And this is the result:

enter image description here

$\endgroup$
  • $\begingroup$ Have a look at Defer and What are the most common pitfalls awaiting new users? $\endgroup$ – ssch Sep 9 '13 at 13:16
  • $\begingroup$ You should use Do[..., {g, 3}] instead of For[g = 1, g < 4, g++, ...];. It's idiomatic, easier to read and maintain, and possibly faster. Or Map, if possible, or some other construct. $\endgroup$ – Volker Sep 9 '13 at 13:17
  • $\begingroup$ @ssch, using defer instead HoldForm@ still prints S_g. $\endgroup$ – user565739 Sep 9 '13 at 13:23
  • 2
    $\begingroup$ Just HoldForm/Defer the S part: Subscript[S, 3] = 4; g = 3; Subscript[Defer[S], g] $\endgroup$ – ssch Sep 9 '13 at 13:32
  • $\begingroup$ You may benefit from this answer which adds automatically symbolic elements with subscript. mathematica.stackexchange.com/questions/22376/… $\endgroup$ – s.s.o Sep 9 '13 at 14:05
3
$\begingroup$

Some options:

Table[Subscript[HoldForm @ S, i], {i, 3}]

Table[With[{i = i}, HoldForm @ Subscript[S, i]], {i, 3}]

Table[i /. x_ :> HoldForm @ Subscript[S, x], {i, 3}]

You could also use Defer as ssch mentioned if you want to be able to use the output as input that evaluates.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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