0
$\begingroup$

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?

$\endgroup$
1
  • 1
    $\begingroup$ Please avoid using subscripts. Some feferences: ref1, ref2, ref3 $\endgroup$ Commented Oct 20, 2015 at 11:40

1 Answer 1

3
$\begingroup$

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]
$\endgroup$
3
  • 2
    $\begingroup$ I'd have used Scan[] myself… $\endgroup$ Commented Oct 20, 2015 at 10:10
  • 1
    $\begingroup$ @J.M. -- Can you elaborate for the sake of posterity? $\endgroup$
    – Jagra
    Commented Oct 20, 2015 at 13:16
  • 3
    $\begingroup$ @Jagra Scan[(x[#] = #) &, indices] $\endgroup$ Commented Oct 20, 2015 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.