I wonder define a bunch variables named like $X_1$, $X_2$, $...$, $X_n$. Is there some smart way to declare them instead of by pure typing. One trick I can image is to use the for loop,For [i = 1, i <= n, i++], to replace the subindices,. However, now each i is not numbers but texts, I don't know how to implement the for loop to texts or text strings. Can anyone give me some hints?

  • 1
    $\begingroup$ Please avoid using subscripts. Some feferences: ref1, ref2, ref3 $\endgroup$ – Dr. belisarius Oct 20 '15 at 11:40

This would be more idiomatic to Mathematica than using a for loop:

indices = {"a", "b", "c"};

Array[(x[indices[[#]]] = #) &, 3];

{x["a"], x["b"], x["c"]}

{1, 2, 3}

This is an equivalent for loop:

For[i = 1, i <= Length[indices], i++,
 x[indices[[i]]] = i]
| improve this answer | |
  • 2
    $\begingroup$ I'd have used Scan[] myself… $\endgroup$ – J. M.'s technical difficulties Oct 20 '15 at 10:10
  • 1
    $\begingroup$ @J.M. -- Can you elaborate for the sake of posterity? $\endgroup$ – Jagra Oct 20 '15 at 13:16
  • 3
    $\begingroup$ @Jagra Scan[(x[#] = #) &, indices] $\endgroup$ – Dr. belisarius Oct 20 '15 at 13:39

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.