2
$\begingroup$

I have a rank 5 tensor that ultimately I want to modify so that for the first 3 dimensions, each element is summed together. The result will be a rank 2 tensor whose elements are the summed totals from the other 3 dimensions.

That was pretty abstract and difficult for me to explain..

But I believe I can achieve the result that I want by using the function Total[].

I see that I can use Total to sum along a single dimension, or multiple dimensions. I'm just a bit confused about exactly how this works.

Can I simply use:

MyArray (*This is the rank 5 tensor*)

Table[MyArray, {1, 2, 3}]; 
(*This is supposed to sum up all elements along indices 1,2,3 , \
leaving behind a rank 2 tensor.*)

Are there any issues with this? Should I instead call Total three separate times?

$\endgroup$
  • 1
    $\begingroup$ Have you tried this: c = ConstantArray[1, {3, 3, 3, 3, 3}]; Total[c, {1, 3}] ? $\endgroup$ – Arnoud Buzing Apr 17 at 16:47
  • 1
    $\begingroup$ Or Total[c, 3]. $\endgroup$ – Henrik Schumacher Apr 17 at 16:56
  • $\begingroup$ So the only difference between this and what I wrote is that you called the indices {1,3} and I called the indices {1,2,3}. Is that correct? Can you clarify why you made this change? $\endgroup$ – LooseyGoose Apr 17 at 16:57
  • 1
    $\begingroup$ Excellent, I think that is what I want to do. Thanks for the help arnould and henrik! $\endgroup$ – LooseyGoose Apr 17 at 17:21
  • 1
    $\begingroup$ @LooseyGoose You're welcome! $\endgroup$ – Henrik Schumacher Apr 17 at 17:38
2
$\begingroup$

A good way to test things is to create an array where all the dimensions are different, and then check the dimensions of the result. So:

array = ConstantArray[1, {2, 3, 4, 5, 6}];
Total[array, 3] //Dimensions

{5, 6}

This shows that Total summed over the first 3 dimensions. Another example:

Total[array, {2, 4}] //Dimensions

{2, 6}

showing that the 3 middle dimensions have been summed over.

$\endgroup$

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.