Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
    
How about m4 /. l : {__Integer} :> foo[l] ? –  mfvonh May 27 at 19:02
    
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. –  mfvonh May 27 at 19:17
    
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] ? –  eldo May 27 at 19:18
    
@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 –  eldo May 27 at 19:27

1 Answer 1

up vote 1 down vote accepted
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]
share|improve this answer
    
Brilliant --------- –  eldo May 27 at 19:23
    
@eldo I'm glad it works as you need. –  Kuba May 27 at 19:28

Your Answer

 
discard

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.