3
$\begingroup$

In numpy, all basic operations can be applied to a specific axis of a given input array, like so:

np.average(an_array,axis=3)

in Mathematica however all functions are always applied to the first dimension apparently:

Dimensions[AnArray]
Dimensions[Mean[AnArray]]

{40, 2, 61, 3}

{2, 61, 3}

When I want to average the third axis I then do:

Dimensions[AnArray]
Dimensions[Transpose[Mean[Transpose[AnArray, {3, 2, 1, 4}]], {2, 1, 3}]]

{40, 2, 61, 3}

{40, 2, 3}

This is very cumbersome. Is there an easier way in Mathematica?

$\endgroup$
1
  • 2
    $\begingroup$ Map takes a level specification. E.g. [Transpose[Mean[Transpose[AnArray, {3, 2, 1, 4}]], {2, 1, 3}] can be written: Map[Mean, AnArray, {2}] $\endgroup$ – Daniel Huber Feb 11 at 17:01
4
$\begingroup$
SeedRandom[1]
anArray = RandomInteger[10, {40, 2, 61, 3}];

meana = Transpose[Mean[Transpose[anArray, {3, 2, 1, 4}]], {2, 1, 3}];
Dimensions[meana]
{40, 2, 3}

axis = 3;

1. Map Mean at level axis - 1:

meanb =  Map[Mean, anArray, {axis - 1}]
Dimensions[meanb]
{40, 2, 3}

2. Flatten with {axis} as the second argument and take Mean:

meanc = Mean @ Flatten[anArray, {axis}];
Dimensions[meanc]
{40, 2, 3}
meana == meanb == meanc
True
$\endgroup$
2
$\begingroup$

For the Mean example, you can use Total instead, which does support other dimensions:

A = RandomInteger[10, {40, 2, 61, 3}];

r1 = Transpose[Mean[Transpose[A, {3, 2, 1, 4}]], {2, 1, 3}];
r2 = Total[A, {3}]/Dimensions[A][[3]];

r1 === r2

True

$\endgroup$
1
  • $\begingroup$ How about other functions? Norm e.g.? $\endgroup$ – Mr Puh Feb 11 at 16:58

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.