Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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]]]]];


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?

share|improve this question
You could nest the Tables – Verbeia Feb 27 '13 at 5:23
up vote 1 down vote accepted

I guess one could do the following using Table

    Table[Table[Table[p = test[[i, j, 1]]; q = test[[i, j, 2]];
 r = Cross[p, q]; mat = Orthogonalize[{p, q, r}]; 
mat.SeparationVector[p, test[[i, k, 1]], 2], {k, 5}], {j, 5}], {i, 10}]
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.