I need to Map a function with certain arguments $f(\alpha,\beta,\gamma,\delta)$ onto a whole tensor.
My current approach looks like
n = 400;
ATensor = Table[{# + i, # + i + 1, # + i + 2, # + i + 3} & /@ Range[n], {i, 1, n}];
f[#1, #2, #3, #4] & @@@ ATensor[[#]] & /@ Range[n]; // AbsoluteTiming
and I end up getting the desired result within the following computation time on my maschine.
{0.0712512, Null}
I'd like to be more efficient when mapping the function onto the tensor so I tried to speed up this computation. I noticed that the majority of time is taken while iterating through every single row because mapping the function onto one row just takes a small amount of time.
f[#1, #2, #3, #4] & @@@ ATensor[[1]]; // AbsoluteTiming
{0.0001304, Null}
Due to the fact that I have to apply functions to tensors with large dimensions I'd like to know if there is a smarter and more efficient way to map the function onto the whole tensor or speed up the iteration through every single row. At this point I am very thankful for any tips on how to improve the computational time.
UPDATE
Fixed the mistake of the indexing mentioned by thorimur.
I implemented the input of thorimur and changed
f[#1, #2, #3, #4] &
tof
with the following speedup (twice as fast)f @@@ ATensor[[#]] & /@ Range[n]; // AbsoluteTiming {0.0298548, Null}
I also tried to use
Apply[f, ATensor, {2}]
and it give the desired result but it is not faster than my approach but more neat I guess.Apply[f, ATensor, {2}]; // AbsoluteTiming {0.0282078, Null}
I tried using
ArrayReduce
aswell and ended up being slower than the first to variantsArrayReduce[Apply[f], ATensor, 3]; // AbsoluteTiming {0.190799, Null}
RepeatedTiming
instead ofAbsoluteTiming
to get more consistent and robust timings. Second, you haven't given us anyf
– Are you sure that it is the mapping and not the actualf
that will be a performance bottleneck in your computation? $\endgroup$