0
$\begingroup$

I regularly want to test if a certain function, here foo, gives the expected result when mapping it over n - level - matrices.

My naive approach is to write:

m1 = Range@3;
m2 = {m1, m1};
m3 = {m2, m2};
m4 = {m3, m3};

Then I test:

Map[foo, m1, {ArrayDepth@m1 - 1}];
(* ... *)
Map[foo, m4, {ArrayDepth@m4 - 1}];

The m1-case correctly gives:

foo[{1, 2, 3}],

and the m4-case correctly gives:

{{{foo[{1, 2, 3}], foo[{1, 2, 3}]}, {foo[{1, 2, 3}], 
   foo[{1, 2, 3}]}}, {{foo[{1, 2, 3}], 
   foo[{1, 2, 3}]}, {foo[{1, 2, 3}], foo[{1, 2, 3}]}}}

(foo should always map over the innermost level).

I am now looking for a more elegant and automated solution, possibly a oneliner like:

(m[#] = BuildLevels[Range@3,4]) & /@ Range@4

but don' t know how to implement it in a short and efficient way.

Thanks in advance for your help.

$\endgroup$
  • $\begingroup$ How about m4 /. l : {__Integer} :> foo[l] ? $\endgroup$ – mfvonh May 27 '14 at 19:02
  • $\begingroup$ Just to add to that. @Kuba's answer will be faster than mine and is generally preferable if your expression has a regular structure. Mine may work better (or at least may require less typing) if the expression is unstructured. So {m1, m2, m3, m4} /. l : {__Integer} :> foo[l] also works. $\endgroup$ – mfvonh May 27 '14 at 19:17
  • $\begingroup$ Dear mfvonh, yes that is elegent and works, but only after having defined m1 ... m4. Dear kuba, "m" doesn't work because it is not defined in the above example. Couldn't one use in this case an automatic assignment to an indexed variable like m[1] ... m[4] ? $\endgroup$ – eldo May 27 '14 at 19:18
  • $\begingroup$ @Kuba - yes, I just wanted to answer "brilliant", but for one reason or the other one has to use at least 15 characters. Many many thanks - D $\endgroup$ – eldo May 27 '14 at 19:27
1
$\begingroup$
m[0] = {1, 2, 3};
m[n_] := m[n] = {#, #} &[m[n - 1]]

And you can test each m[i] with:

Map[foo, m[5], {-2}]
{{{{{foo[{1,2,3}],foo[{1,2,3}]},{foo[{1,2,3}],foo[{1,2,3}]}},{{foo[{1,2,3}],foo[{1,2,3}]},{foo[{1,2,3}],foo[{1,2,3}]}}},{{<<1>>,{<<1>>}},<<1>>}},<<1>>}

or different approach:

    ClearAll[mm]
mm[0] = {1, 2, 3};
mm[n_] := Nest[Partition[#, 2] &, ConstantArray[mm[0], 2^(n)], n - 1]
$\endgroup$
  • $\begingroup$ Brilliant --------- $\endgroup$ – eldo May 27 '14 at 19:23
  • $\begingroup$ @eldo I'm glad it works as you need. $\endgroup$ – Kuba May 27 '14 at 19:28

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.