# Applying a function along the desired dimensions of a n-dimensional array

I am trying to apply an arbitrary function f that takes several inputs and returns a scalar along some specific dimensions of an n-dimensionnal array.

Here is an example of how I proceed for now (supposing the arbitrary function f is Mean ) :

aa = {ConstantArray[1, 4], ConstantArray[2, 4], ConstantArray[3, 4]};
a = {aa, aa, aa};


Suppose I want the mean of a along the dimension (or should I say level?) 2, I do :

Table[Mean[a[[ii, ;;, jj]] ], {ii, Dimensions[a][[1]]} , {jj, Dimensions[a][[3]]} ]


Which yields : {{2, 2, 2, 2}, {2, 2, 2, 2}, {2, 2, 2, 2}} as expected.

I would like to implement a function that would enable me to compute any function f (that takes several inputs and spits out a scalar just like Mean does) over any arbitrary set of the dimensions of a n-dimensionnal array.

I feel like I could do something with Map and recursive functions such as [there]{Mapping a function over n levels} but I fail to see how to do. Or maybe this is not the right way to do it...

Any hint would be appreciated.

• Do you mean something like Map[f@@##&, expr, {level}]? Or just Map[f, expr, {level}], depending on whether f actually takes one list, or a Sequence of values. Here we can reproduce your result with a simple Map[Mean, a, {1}] or Mean /@ a... May 1, 2017 at 16:39
• @MariusLadegårdMeyer I guess it could be something of the kind, however if I naively try your suggestion adapted to my example : Map[Mean @@ ## &, a, 2] it doesn't yield the expected value.
– Mary
May 1, 2017 at 16:44
• That's because Mean does not take several input arguments, but one list of arguments. The lists you are passing to Mean in your Table are lists of all elements at level 2, for a given first index ii... But those lists are what you find at level 1! So just Mean /@ a is what you need in your example, as I've written above. May 1, 2017 at 16:48
• If you can make an example of a function that needs a sequence of several arguments, and not a list of arguments, (one argument), then we can try to deal with that. May 1, 2017 at 16:50
• Mean /@ a indeed works for this specific example which I voluntarily kept simple (maybe too simple then), but it does not apply for any set of levels as I required further in the question. As for your remark about Mean that takes one list of arguments, thanks for pointing that out ! That is indeed what I would like to have : a function that takes one list of scalar arguments and spits out a single scalar. The problem lies in defining that list in a general and versatile way.
– Mary
May 1, 2017 at 16:57