Re: Performance of Array Addition
- To: mathgroup at smc.vnet.net
- Subject: [mg90979] Re: Performance of Array Addition
- From: Albert Retey <awnl at gmx-topmail.de>
- Date: Fri, 1 Aug 2008 03:01:43 -0400 (EDT)
- References: <g6rnv9$7lj$1@smc.vnet.net>
Hi Jeremy,
> Let there be, for example, an array of reals with dimensions
> {d1,d2,3}.
>
> I have noticed that the command
>
> array[[All,All,1]] + array[[All,All,2]] + array[[All,All,3]];
>
> is much faster than
>
> Map[Total, array, {2}];
>
> even though they return the same answer.
>
> The advantage of Map[Total, array, {2}] is that it allows arrays of
> dimension {d1,d2,d3}, with d3 arbitrary.
>
> Is there a way to get closer to the speed advantages of hand-coding
> the addition of the final dimension, while
> allowing the number of elements in the final dimension to be
> arbitrary?
yes
This is my first try, it just literally does programmatically what you
have done for 3:
Plus@@Table[array[[All, All, i]], {i, 1, Last[Dimensions[array]]}]
But if you look at the documentation for Total you will find that it
accepts additional arguments:
Total[array, {3}]
or:
Total[array,{Total[array, {Depth[array] - 1}]}]
which is even faster by a factor of about 3 on my machine...
hth,
albert