I want to change indices of matrix name during loop for creating different matrices. For example;

   Ki={{i,2*i},{3*i,4*i}};   (* i subscript)

(* to generate K1, K2,....K5 *)

I need help on this.

  • $\begingroup$ For[i = 1, i <= 5, i++, K[i] = {{i, 2*i}, {3*i, 4*i}}] will generate K[1],K[2],... $\endgroup$
    – Stelios
    Oct 18, 2015 at 9:33
  • 1
    $\begingroup$ It's bad practice to use subscripts as variables - I'm sure we have a canonical answer somewhere, but mathematica.stackexchange.com/questions/1004/… and mathematica.stackexchange.com/a/13782/30771 $\endgroup$ Oct 18, 2015 at 9:39
  • $\begingroup$ Did the answer below answer your question? If so, please accept it by clicking the grey question mark to the left of the answer! $\endgroup$
    – march
    Dec 8, 2015 at 16:27

1 Answer 1


For pedagogical purposes:

  • In general, using Subscripts to define variables is a bad idea in Mathematica. In your problem, I suggest either using k[n] or defining a List ks where each element is one of your matrices.

  • Avoid using capital letters when defining variables. All Mathematica built-ins start with capital letters; for instance, K is a reserved symbol in Mathematica, so using it might cause problems.

  • There are syntax errors in your For loop. To make it do what you want, here would be the correct syntax:

    Clear[i, k]
    For[i = 1, i <= 5, i++
      , k[i] = {{i, 2*i}, {3*i, 4*i}}

However, in Mathematica, it is often beneficial to avoid loops. Here are a couple of alternatives to the method you've outlined.

  • Use Do:

    Do[k[i] = {{i, 2*i}, {3*i, 4*i}}, {i, 1, 5}]
  • Use a Table to construct a list of k's. You can get parts of lists using [[ <> ]]:

    ks = Table[{{i, 2*i}, {3*i, 4*i}}, {i, 1, 5}];
    (* {{2, 4}, {6, 8}} *)
  • Use Scan in order to evaluate a function with side effects while avoiding any outputs.

    f[num_] := k[num] = {{num, 2*num}, {3*num, 4*num}}
    Scan[f, {1, 2, 3, 4, 5}]
  • Take advantage of built-ins and pure functions with Scan:

    Scan[(k[#] = Partition[# Range[4], 2]) &, Range[5]]
  • Map a function that creates the matrices over a set of inputs:

    ks = Partition[Range[#, 4 #, #], 2] & /@ Range[5]

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.