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.
Map[f@@##&, expr, {level}]
? Or justMap[f, expr, {level}]
, depending on whetherf
actually takes one list, or aSequence
of values. Here we can reproduce your result with a simpleMap[Mean, a, {1}]
orMean /@ a
... $\endgroup$Map[Mean @@ ## &, a, 2]
it doesn't yield the expected value. $\endgroup$Mean
does not take several input arguments, but one list of arguments. The lists you are passing toMean
in yourTable
are lists of all elements at level 2, for a given first indexii
... But those lists are what you find at level 1! So justMean /@ a
is what you need in your example, as I've written above. $\endgroup$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 aboutMean
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. $\endgroup$