For pedagogical purposes:
In general, using
Subscript
s to define variables is a bad idea in Mathematica. In your problem, I suggest either usingk[n]
or defining aList
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 loopsbeneficial 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 ofk
's. You can get parts of lists using[[ <> ]]
:ks = Table[{{i, 2*i}, {3*i, 4*i}}, {i, 1, 5}]; ks[[2]] (* {{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]