# Avoiding unnecessary computations within loops

Consider the following data:

test = RandomReal[{1, 2}, {10, 5, 3, 3}];


How can I do the following without the For loops, e.g. using Table or similar Mathematica functions?

Module[{res = {}},
For[i = 1, i < 11, i++,
For[j = 1, j < 6, j++,
p = test[[i, j, 1]];
q = test[[i, j, 2]];
r = Cross[p,q];
mat = Orthogonalize[{p, q, r}];
For[k = 1, k < 6, k++,
AppendTo[res, mat.SeparationVector[p, test[[i, k, 1]], 2]]]]];
res]


where

SeparationVector[x_, y_, z_] := If[# < z/2, x - y, Sequence @@ {}]& @
Sqrt[Total[((x - y) - z*Round[(x - y)/z])^2]]


My Problem with using Table is that between the j and k indices, I define variables that depend on j so that I don't have to calculate these values for every iteration of k. I don't know how to achieve the same functionality without the For loops. But this is Mathematica, and I know there are better and faster ways to do this. Any ideas?

-
You could nest the Tables –  Verbeia Feb 27 '13 at 5:23

I guess one could do the following using Table
    Table[Table[Table[p = test[[i, j, 1]]; q = test[[i, j, 2]];