I would like to implement a simplified version of Outer
(Outer[f, vec1, vec2,..]
) through a looping construct.
Here are is one thing that works, but is not quite down to the level I'd like it to be on (think, say, what is a available in C). Using Table
one could do the following:
v1 = {a, b, c};
v2 = {A, B, C, D};
Table[Table[f[i, j], {j, v2}], {i, v1}] === Outer[f, v1, v2]
True
I know that the result should be of the form (this is correct for n vectors):
lsts = {v1, v2};
res = ConstantArray[0, Join[Length /@ lsts, {Length[lsts]}]]
A Do
loop would look like this:
Do[
Do[
res[[j, i, 1]] = lsts[[1, j]];
res[[j, i, 2]] = lsts[[2, i]];
, {i, Length[lsts[[2]]]}]
, {j, Length[lsts[[1]]]}]
res == Outer[List, lsts[[1]], lsts[[2]]]
True
My question is how would I generalize the do loop for n vectors?
Mathics does this via recursion. Looking at the output of a compiled outer did not give an idea either:
cf = Compile[{}, Outer[List, {1, 2, 3}, {4, 5, 6}]];
Needs["CompiledFunctionTools`"]
CompilePrint[cf]
Do
-loop code using metaprogramming. However one usually wishes to go the other direction in Mathematica, i.e. convert verbose loops into concise high-level abstractions such asOuter
, therefore I echo Sascha's question: why? If you explain the purpose behind this question it is likely that you will get more useful replies that if you do not. $\endgroup$