# Help with sum specific elements of a matrix in mathematica

I am trying to sum over specific indices in a matrix.

For example, if I have the matrix

a = {{1, 2, 3, 3}, {4, 5, 6, 6}, {7, 8, 9, 9}, {1, 5, 9, 7}}


i need to sum the index {2, 1} and {4, 3} , i.e 4 + 9 = 13 automatically.

I try the code

Sum[a[[ii]][[jj]], {ii, 2, 4, 2}, {jj, 1, 4 , 2}]


and this is equals to 20. (WTF) (i think this shows the result of 4+6+1+9) Why?

In a general form I need to compute the sum of indices {2, 1}, {4, 3}, {6, 5}, {8, 7}, {10, 9}, {12, 11}, {14,13}, {16,15} for a 16x16 square matrix.

Thanks for the help

Regards

a = {{1, 2, 3, 3}, {4, 5, 6, 6}, {7, 8, 9, 9}, {1, 5, 9, 7}};
positions = {{2, 1}, {4, 3}};
Total@Extract[a, positions]

• thanks bro. your answer was useful – smath Oct 13 '18 at 20:21

To see why it doesn't work as you expected, look at the indices that you generated.

Table[{ii, jj}, {ii, 2, 4, 2}, {jj, 1, 4, 2}]

(* {{{2, 1}, {2, 3}}, {{4, 1}, {4, 3}}} *)


You generated four indices so the sum was over four entries. Use

a = {{1, 2, 3, 3}, {4, 5, 6, 6}, {7, 8, 9, 9}, {1, 5, 9, 7}};

Sum[a[[Sequence @@ i]], {i, {{2, 1}, {4, 3}}}]

(* 13 *)

• thanks, now i can understand my problem – smath Oct 13 '18 at 20:22

I would have used Extract if Alan had not posted it first.

So, here is a way to use Sum:

Sum[a[[## & @@ i]], {i, {{2, 1}, {4, 3}}}]


13

But that is also posted a minute earlier by Bob Hanlon.

That leaves

☺ = {♯, ♯♯} \[Function] +## & @@ (♯[[##]] & @@@ ♯♯);
☺[a, {{2, 1}, {4, 3}}]


13

and

☺☺ = +## & @@ (♯ \[Function] #[[## & @@ ♯]]) /@ #2 &;
☺☺[a, {{2, 1}, {4, 3}}]


13

a = {{1, 2, 3, 3}, {4, 5, 6, 6}, {7, 8, 9, 9}, {1, 5, 9, 7}};
a[[##]] & @@@ Thread@Range[{2, 1}, {4, 3}, 2] // Total


13

Where you would replace {4,3} with {16,15} in Range for the bigger matrix.

a[[Sequence @@ #]] & /@ {{2, 1}, {4, 3}} // Total


13

Just for giggles, and using your $$16\times 16$$ example:

Tr[IdentityMatrix[[Range[2 ,16, 2]]].
Array[C, {16, 16}].
Transpose[IdentityMatrix[[Range[1, 15, 2]]]]]

• (I am still stuck on gedanken Mathematica, but I believe that ought to work.) – J. M. is in limbo Oct 13 '18 at 4:40
• wow. is beautiful – smath Oct 13 '18 at 20:27