0
$\begingroup$

I want to print

A[0, 0, 1], A[0, 0, 2], A[1, 1, 1], A[1, 1, 2], A[2, 2, 1], A[2, 2, 2] 

using the following code.

For[t = 0, t < 3, t = t + 1, 
  For[z = 0, z < 3, z = z + 1, 
    For[i = 1, i < 3, i++, Print[A[t, z, i]]]]]
$\endgroup$
1
6
$\begingroup$

Why exactly you need a loop if you don't want to loop is completely beyond my understanding, but maybe you have processor time to kill or something like that.. Anyway

For[t = 0, t < 3, t++,
 For[z = 0, z < 7, z++,
  For[i = 1, i < 3, i++,
   If[t == z,
    Print[A[t, z, i]
     ]
    ]
   ]
  ]
 ]
(*
A[0,0,1]

A[0,0,2]

A[1,1,1]

A[1,1,2]

A[2,2,1]

A[2,2,2]
*)
$\endgroup$
1
  • $\begingroup$ Guys, really?? So many upvotes for such a lousy idea? Note to myself: Don't write answers in sarcastic mode. $\endgroup$
    – halirutan
    Jul 6 '17 at 15:32
8
$\begingroup$
Array[A[#, #, #2] &, {3, 2}, {0, 1}, Flatten[{##},1]&]
Flatten @ Table[A[i, i, j], {i, 0, 2}, {j, 1, 2}]

both give

{A[0, 0, 1], A[0, 0, 2], A[1, 1, 1], A[1, 1, 2], A[2, 2, 1], A[2, 2, 2]}

$\endgroup$
6
$\begingroup$

By pushing the If up into the 2nd loop, this code wastes a little less processor time than Harlirutan's solution.

For[t = 0, t < 3, t++,
  For[z = 0, z < 3, z++,
    If[z == t, For[i = 1, i < 3, i++, Print[A[t, z, i]]]]]]

result

$\endgroup$

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.