1
$\begingroup$

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?

$\endgroup$
1
  • $\begingroup$ You could nest the Tables $\endgroup$
    – Verbeia
    Feb 27, 2013 at 5:23

1 Answer 1

1
$\begingroup$

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}]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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