# A loop in which three indices are changed

How could this piece of code be written in the Table, or as simply as possible?

ClearAll["Global*"]
LL = {1, 2, 3, 4, 5, 4};

n = 1;
For[i = 1, i <= 2, i++,
For[j = 1, j <= 3, j++, {a[i, j] = LL[[n]], n = n + 1}]]

(*a[2, 3]

4*)


## 3 Answers

### Table

ClearAll[a]
Table[a[i, j] = Partition[LL, 3][[i, j]], {i, 1, 2}, {j, 1, 3}];

{a[1, 3], a[2, 2], a[2, 3]}

 {3, 5, 4}

ClearAll[a]
Table[a[i, j] = LL[[3 (i - 1)  + j]], {i, 1, 2}, {j, 1, 3}];

{a[1, 3], a[2, 2], a[2, 3]}

 {3, 5, 4}


### Array

ClearAll[b]
Array[(b[##] = Partition[LL, 3][[##]]) &, {2, 3}];

{b[1, 3], b[2, 2], b[2, 3]}

{3, 5, 4}

ClearAll[b]
Array[(b[##] = LL[[3 (# - 1) + #2]]) &, {2, 3}];

{b[1, 3], b[2, 2], b[2, 3]}

{3, 5, 4}


### Do

ClearAll[c]
Do[c[Ceiling[k/3], Mod[k, 3, 1]] = LL[[k]], {k, Length @ LL}]

{c[1, 3], c[2, 2], c[2, 3]}

 {3, 5, 4}


### MapIndexed

ClearAll[d]
MapIndexed[(d[Ceiling[#2[[1]]/3], Mod[#2[[1]], 3, 1]] = #) &]@LL;

{d[1, 3], d[2, 2], d[2, 3]}

 {3, 5, 4}


### Scan

ClearAll[e]
Scan[Apply[(e[##] = LL[[#2 + 3 (# - 1)]]) &], Tuples[Range /@ {2, 3}]]

{e[1, 3], e[2, 2], e[2, 3]}

{3, 5, 4}


### MapIndexed + Scan

ClearAll[f]
Scan[MapApply[(f[#2, #3] = #) &],
MapIndexed[Flatten@{##} &, Partition[LL, 3], {2}]]

{f[1, 3], f[2, 2], f[2, 3]}

 {3, 5, 4}


How could this piece of code be written in the Table, or as simple as possible?

I would just replace the For by Do to keep things simpler and more clear

ClearAll["Global*"]
LL = {1, 2, 3, 4, 5, 4};
n = 1;
Do[
Do[a[i, j] = LL[[n++]], {j, 1, 3}],
{i, 1, 2}
]


Or are you looking for something using more fancy things like #&/@..\/@@##* in order to make the code shorter?

Try to avoid For. It is not really needed in Mathematica. I think Wolfram added it in order to help attract the C/C++ programmers to Mathematica.

Another solution using Array and ArrayReshape:

Clear[a]

LL = {1, 2, 3, 4, 5, 4};

Evaluate@Array[a, {2, 3}] = ArrayReshape[LL, {2, 3}];

a[2, 3]
(* 4 *)


But why not simply define a as a List? If you feel the [[]] too long to type, or need symbolic indexed notation in the first place e.g. Clear[a]; a[[1, 2]] + a[[2, 3]] but don't want to see the warning, then just make use of Subscript (you can input it easily by pressing Ctrl+-) and Indexed:

Clear[a, Subscript]

Subscript[a_, b__] := Indexed[a, {b}];

Subscript[a, 1, 3] + Subscript[a, 2, 2]
(* Indexed[a, {1, 3}] + Indexed[a, {2, 2}] *)

a = ArrayReshape[LL, {2, 3}];

Subscript[a, 1, 3] + Subscript[a, 2, 2]
(* 8 *)